开发者

How to start two threads at "exactly" the same time

The threads should start at same split second. I understand, if you do thread1.st开发者_StackOverflow中文版art(), it will take some milliseconds before the next execution of thread2.start().

Is it even possible or impossible?


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");

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

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.


You could use a CountDownLatch for this. Please find below a sample. Though t1 and t2 are started, these threads keep waiting till the main thread counts down the latch. The number of countdowns required is mentioned in the constructor. Countdown latch can also be used to wait for threads to finish execution so that the main thread can proceed further(the reverse case). This class was included since Java 1.5.

import java.util.concurrent.CountDownLatch;


public class ThreadExample
{
    public static void main(String[] args) 
    {
        CountDownLatch latch = new CountDownLatch(1);
        MyThread t1 = new MyThread(latch);
        MyThread t2 = new MyThread(latch);
        new Thread(t1).start();
        new Thread(t2).start();
        //Do whatever you want
        latch.countDown();          //This will inform all the threads to start
        //Continue to do whatever
    }
}

class MyThread implements Runnable
{
    CountDownLatch latch;
    public MyThread(CountDownLatch latch) 
    {
        this.latch = latch;
    }
    @Override
    public void run() 
    {
        try 
        {
            latch.await();          //The thread keeps waiting till it is informed
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Do the actual thing
    }
}


It is not possible, at least on a single core computer. But why do you want that? Even if you were able to start two threads at exactly the same second, they will progress differently because scheduling is not in your control.

Edit: (In response to some of the comments) It is a perfectly valid requirement to synchronize the state or progress of multiple threads and CyclicBarrier is a great tool. I answered the question whether it is possible to start multiple threads at exactly the same time. CyclicBarrier will guarantee that the threads proceed when they are exactly at the desired state but it doesn't guarantee that they will start or resume at exactly the same time, although it might be pretty close. There's no mention of synchronization needs in the question.


  1. As I understand it, the JVM mostly delegates this stuff to the operating system. So the answer will be OS-specific.
  2. It is clearly impossible on a single-processor machines.
  3. It is more complicated with respect to a multi-processor machine. According to the Relativity of simultaneity, "it is impossible to say in an absolute sense whether two events occur at the same time if those events are separated in space." No matter how close your processors are, they are separated in space.
    1. If you can accept relative simultaneity, then it is probably easier just to simulate it using techniques discussed in other responses.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜