views:

404

answers:

6

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(). Is it even possible or impossible?

+1  A: 

I see two ways to do this.

A. Start them both from two different threads. Use Thread.sleep() to wait until the exact same millisecond in both threads, and then start them.

B. Start them from the same thread, but alter each thread so that it uses Thread.sleep() to wait until exactly the same millisecond before really starting.

Erick Robertson
Neither of those approaches will be reliable ... unless you use a (hypothetical) hard-realtime JVM that used (hypothetical) hard-realtime thread support in the OS. Even then, you need multiple cores.
Stephen C
I don't think the person who asked the question understands any of this stuff. I do, but I'm just trying to give him an answer he can use.
Erick Robertson
+8  A: 

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.

Samit G.
You can get pretty darn close though. It all depends on the synchronization techniques you use *and of course having more than 1 cpu or core.*
ChaosPandion
The idea is that this is wrong-headed approach and should not be necessary in any not-hard-real-time environment, not that it's "pretty close".
Nikolai N Fetissov
Even in a very simple performance test for modules, synchronizing the "start of processing" is very much necessary to obtain valid data.. And damn close is much preferable in such cases.
Enno Shioji
It is *also* impossible because Java thread scheduling does not give you millisecond accuracy.
Stephen C
@Nikolai - I totally agree. And the OP doesn't want darn close. OP wants *same split second*
Samit G.
@Zwei - you can probably get "damn close" most of the time on an otherwise idle machine. But if you need it all of the time, you need to program in a language like C, on a machine with hard realtime support in the OS. Consider also that the JVM might be running a full GC at the "split second" you want to start your threads.
Stephen C
@Stephen - Exactly. I think even sleep is not *guaranteed* to be accurate down to a millisecond.
Samit G.
@Stephen: Yes, I agree. But there is still value in doing this because at least you can prevent having full GC between the start of t1/t2, etc. That kind of preparation is necessary to make performance data as reliable as possible. But then again I agree that we should be warning the OP about your point.. So +1 for the answer!
Enno Shioji
It is a perfectly valid synchronization problem. Threads need to initialize some data, make sure that no one goes into a critical region without proper validation. And the fact that CyclicBerrier is included in javas concurrent package means that this an important problem.
tulskiy
+18  A: 

There is a class for that. CyclicBarrier

To start the threads at exactly the same time (at least as good as possible), do this:

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

EDIT (from my comment above..): Synchronizing between threads is indeed a very common necessity. Yes in java you can't have them executing exactly in parallel (which, on other platform can be a very valid requirement btw), but from time to time it is very common that you need to synchronize their action.

Enno Shioji
+1 nice thinking ;-) Although of course it doesn't make the threads start at _exactly_ the same time in real time (at least not on a single-core chip, and not guaranteed even on a multi-core chip), but I can't think of any way to do better.
David Zaslavsky
Will this hook into environment specific wait handles?
ChaosPandion
@ChaosPandion: Care to elaborate?
Santa
@Santa - The Win32 API for example offers different primitives. One useful type is the manual reset event returned when you call `CreateEvent`. http://msdn.microsoft.com/en-us/library/ms686364%28VS.85%29.aspx
ChaosPandion
@ChaosPandion: I'm not sure what exact primitive operation (wait/notify? spinning?) it uses, but I can assure you that it will perform excellent. This class was done by concurrency wizards ;)
Enno Shioji
@Zwei - Well, whatever it is, this is the answer I would have posted had I been a Java guru.
ChaosPandion
+1 I remember doing the barrier problem in my OS class for several distributed nodes in C. It was a mess.
tulskiy
A: 
  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.
emory
+1 need more spacetime references on SO
msw
A: 

(a) Define 'split second'. (b) Why? (c) How will you be able to tell that it did or didn't happen?

EJP
+2  A: 

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
    }
}
aNish