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