首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有一种方法可以让多个线程打印当前时间(以毫秒为单位)完全相同?

有没有一种方法可以让多个线程打印当前时间(以毫秒为单位)完全相同?
EN

Stack Overflow用户
提问于 2020-04-09 19:24:20
回答 1查看 123关注 0票数 1

使用Executor Service,我需要运行10个线程。每个线程都应该打印当前时间(以毫秒为单位),我需要确保所有这些线程总是打印完全相同的时间。我试过使用CyclicBarrier,但它不起作用。

这样做是可能的吗?

EN

回答 1

Stack Overflow用户

发布于 2020-04-09 19:36:56

您可以使用CountDownLatch来实现您正在尝试的功能;

代码语言:javascript
运行
复制
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池

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61120041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档