一尘不染

Java 如何同时启动两个线程

java

程应在同一瞬间开始。我了解,如果你这样做thread1.start(),则下次执行之前需要花费几毫秒的时间thread2.start()

可能还是不可能?线程应该在同一瞬间开始。我知道,如果你执行thread1.start(),则下次执行thread2.start()需要几毫秒。

这是可能的还是不可能的?


阅读 759

收藏
2020-03-24

共1个答案

一尘不染

要完全同时(至少尽可能好)启动线程,可以使用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

这仍然无法确保它们已正确启动

在其他平台上,确切地说启动线程可能是非常有效的要求。

2020-03-24