码上敲享录 > java高并发常见问题 > java如何保证先启动的线程先执行某段代码

java如何保证先启动的线程先执行某段代码

上一章章节目录下一章 2019-08-23已有1548人阅读 评论(0)

java如何保证先启动的线程先执行某段代码


解决方法:

使用jdk并发包中的Semaphore的公平信号

1.业务代码

import java.util.concurrent.Semaphore;

public class YourService {

private Semaphore semaphore = new Semaphore(1,true);

public void getName() {

try {

semaphore.acquire();

System.out.println("线程名称:" +Thread.currentThread().getName());

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

semaphore.release();

}

}

}


2.线程

public class YourThread extends Thread {

private YourService yourService;

public YourThread(YourService yourService) {

super();

this.yourService = yourService;

}

@Override

public void run() {

System.out.println(this.getName()+ "现在启动了!");

yourService.getName();

}

}


3.测试类

public static void main(String[] args) {

YourService service = new YourService();

YourThread[] threads = new YourThread[3];

for (int i = 0; i < 3; i++) {

threads[i] = new YourThread(service);

threads[i].start();

}

}



4.结果,先启动的线程先执行getName方法

ThreadName-0现在启动了!

ThreadName-2现在启动了!

ThreadName-1现在启动了!

线程名称:ThreadName-0

线程名称:ThreadName-2

线程名称:ThreadName-1


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交