可以 wait()、notify() 实现;也可以使用发令枪 CountDownLatch 实现。
CountDownLatch 实现较简单,如下:
package constxiong.interview;
import java.util.concurrent.CountDownLatch;
/**
* 测试同时启动多个线程
* @author ConstXiong
*/
public class TestCountDownLatch {
private static CountDownLatch cld = new CountDownLatch(10);
public static void main(String[] args) {
for (int i = 0; i <10; i++) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
cld.await();//将线程阻塞在此,等待所有线程都调用完start()方法,一起执行
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis());
}
});
t.start();
cld.countDown();
}
}
}
微信小程序阅读
刷题面试、行情交流 加好友回 666 入群