英文:
Is there a way in which multiple threads can print the current time(Time in milli seconds) exactly same?
问题
使用Executor Service,我需要运行10个线程。而且每个线程都应该打印出当前的毫秒时间,并且我需要确保所有这些线程始终打印出完全相同的时间。
我已经尝试使用CyclicBarrier,但它不起作用。
这样做有可能吗?
英文:
Using Executor Service's I need to run 10 threads. And each of these threads should print the current time in milliseconds and I need to ensure that all these threads always print the exact same time.
I have tried using CyclicBarrier but it does not work.
Is it possible to do so?
答案1
得分: 2
你可以使用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();
}
});
}
}
}
结果
> pool-1-thread-5 - 1586432194060
> pool-1-thread-8 - 1586432194060
> pool-1-thread-4 - 1586432194060
> pool-1-thread-6 - 1586432194060
> pool-1-thread-1 - 1586432194060
> pool-1-thread-2 - 1586432194060
> pool-1-thread-9 - 1586432194060
> pool-1-thread-3 - 1586432194060
> pool-1-thread-7 - 1586432194060
> pool-1-thread-10 - 1586432194060
英文:
You can make use of a CountDownLatch
to achieve what you are trying;
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();
}
});
}
}
}
Result
> pool-1-thread-5 - 1586432194060
> pool-1-thread-8 - 1586432194060
> pool-1-thread-4 - 1586432194060
> pool-1-thread-6 - 1586432194060
> pool-1-thread-1 - 1586432194060
> pool-1-thread-2 - 1586432194060
> pool-1-thread-9 - 1586432194060
> pool-1-thread-3 - 1586432194060
> pool-1-thread-7 - 1586432194060
> pool-1-thread-10 - 1586432194060
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论