如何在“精确"处启动两个线程同时 [英] How to start two threads at "exactly" the same time

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

问题描述

线程应该在同一瞬间开始.我明白,如果你执行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.

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

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

这篇关于如何在“精确"处启动两个线程同时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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