使用Executor Service,我需要运行10个线程。每个线程都应该打印当前时间(以毫秒为单位),我需要确保所有这些线程总是打印完全相同的时间。我试过使用CyclicBarrier,但它不起作用。
这样做是可能的吗?
发布于 2020-04-09 19:36:56
您可以使用CountDownLatch来实现您正在尝试的功能;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestApp {
private static final int THREAD_COUNT = 10;
public static void main(String... args) throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);
for(int i=0;i<THREAD_COUNT;i++) {
executorService.execute(() -> {
countDownLatch.countDown();
try {
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
}
}结果
池-1-线程-5- 1586432194060池-1-线程-8- 1586432194060池-1-线程-4- 1586432194060池-1-线程-6- 1586432194060池-1-线程-1- 1586432194060池-1-线程-2- 1586432194060池-1-线程-9- 1586432194060池-1-线程-3- 1586432194060池-1-线程-7- 1586432194060池-1-线程-10-1586432194060池-1-线程-10-1586432194060池
https://stackoverflow.com/questions/61120041
复制相似问题