如何以“完全”的方式启动两个线程同一时间 [英] How to start two threads at "exactly" the same time

查看:138
本文介绍了如何以“完全”的方式启动两个线程同一时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

线程应该以相同的瞬间开始。我明白,如果你做 thread1.start(),那么在下次执行 thread2.start()

The threads should start at same split second. I understand, if you do thread1.start(), it will take some milliseconds before the next execution of thread2.start().

甚至可能还是不可能?

推荐答案

要在完全相同的时间启动线程(至少尽可能好),可以使用 CyclicBarrier

To start the threads at exactly the same time (at least as good as possible), you can use a CyclicBarrier:

// We want to start just 2 threads at the same time, but let's control that 
// timing from the main thread. That's why we have 3 "parties" instead of 2.
final CyclicBarrier gate = new CyclicBarrier(3);

Thread t1 = new Thread(){
    public void run(){
        gate.await();
        //do stuff    
    }};
Thread t2 = new Thread(){
    public void run(){
        gate.await();
        //do stuff    
    }};

t1.start();
t2.start();

// At this point, t1 and t2 are blocking on the gate. 
// Since we gave "3" as the argument, gate is not opened yet.
// Now if we block on the gate from the main thread, it will open
// and all threads will start to do stuff!

gate.await();
System.out.println("all threads started");

这不一定是 CyclicBarrier ,你也可以使用 CountDownLatch 甚至是锁。

This doesn't have to be a CyclicBarrier, you could also use a CountDownLatch or even a lock.

这仍然无法确保它们在标准JVM上同时完全启动,但您可以非常接近。当你进行性能测试时,相当接近仍然很有用。例如,如果您正在尝试测量具有不同线程数的数据结构的吞吐量,您希望使用这种结构来获得最准确的结果。

This still can't make sure that they are started exactly at the same time on standard JVMs, but you can get pretty close. Getting pretty close is still useful when you do for example performance tests. E.g., if you are trying to measure throughput of a data structure with different number of threads hitting it, you want to use this kind of construct to get the most accurate result possible.

在其他平台上,启动线程完全可能是一个非常有效的要求btw。

On other platforms, starting threads exactly can be a very valid requirement btw.

这篇关于如何以“完全”的方式启动两个线程同一时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆