参考答案
保证多个线程同时启动,可以 wait()、notify() 实现,也可以使用发令枪 CountDownLatch 实现。
CountDownLatch 实现较简单,实例:
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();
}
}
}
以上,是Java面试题【如何保证多个线程同时启动】的参考答案。
输出,是最好的学习方法。
欢迎在评论区留下你的问题、笔记或知识点补充~
—end—
