【问题标题】:Is there a way in which multiple threads can print the current time(Time in milli seconds) exactly same?有没有一种方法可以让多个线程完全一样地打印当前时间(以毫秒为单位的时间)?
【发布时间】:2020-07-22 00:10:17
【问题描述】:

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

有可能吗?

【问题讨论】:

  • 能否请您添加一个您的最佳尝试的代码示例?
  • 预先捕获时间值,将其提供给所有线程并让它们打印出来。现在按照要求“所有线程总是在完全相同的时间打印”。当然,运行 10 分钟后,它们仍会打印开始时间,但您确实说过它们应该始终打印 same 时间。
  • 正如@Andreas 所说,肯定的方法是所有线程都从同一源获取“当前”时间。只要你确保他们都这样做,他们可能会刷新他们的时间(在 10 分钟或更早之后)。

标签: java multithreading datetime threadpool executorservice


【解决方案1】:

您可以使用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

【讨论】:

  • 辛苦了,但这个程序没有保证所有十个线程将总是从时钟读取相同的值。
  • 是的,这是我能得到的最接近的。我需要在所有线程中使用完全相同的值,然后需要从外部传递一毫秒的值。
猜你喜欢
  • 2011-03-09
  • 2010-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 2017-02-20
相关资源
最近更新 更多