110

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?

6
  • 2
    Split second is a very long time at GHz speeds. Jul 31, 2010 at 3:01
  • 42
    No need to downvote so intensely. Not everyone understands threading-related nondeterminism, and we all have to start somewhere. Jul 31, 2010 at 3:07
  • 9
    Don't understand the downvotes. Synchronizing between threads is 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. That's why the jdk has classes for doing that. Maybe the wording was not accurate, but hell if he'd know that, he wouldn't have asked the question.. Jul 31, 2010 at 3:19
  • well, I guess I understand all your anger. It was a question asked to me in an interview...probably was a trick Q. But, I just got confused and wanted to confirm it. that's why I asked if it was even possible.
    – figaro
    Jul 31, 2010 at 3:49
  • 2
    @javaguy - not a "trick" question. Rather a question chosen to see how well you really understand multi-threaded programming in general ... as well in the Java case.
    – Stephen C
    Jul 31, 2010 at 4:04

5 Answers 5

156

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.

13
  • 6
    +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 Z
    Jul 31, 2010 at 3:20
  • Will this hook into environment specific wait handles? Jul 31, 2010 at 3:20
  • @Santa - The Win32 API for example offers different primitives. One useful type is the manual reset event returned when you call CreateEvent. msdn.microsoft.com/en-us/library/ms686364%28VS.85%29.aspx Jul 31, 2010 at 3:27
  • 1
    @Zwei - Well, whatever it is, this is the answer I would have posted had I been a Java guru. Jul 31, 2010 at 3:55
  • +1 I remember doing the barrier problem in my OS class for several distributed nodes in C. It was a mess. Jul 31, 2010 at 17:39
20

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
    }
}
0
18

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.

10
  • 1
    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. Jul 31, 2010 at 3:05
  • 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". Jul 31, 2010 at 3:08
  • 1
    It is also impossible because Java thread scheduling does not give you millisecond accuracy.
    – Stephen C
    Jul 31, 2010 at 3:25
  • 1
    @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
    Jul 31, 2010 at 3:27
  • 1
    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. Jul 31, 2010 at 17:44
7
  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.
1
  • 2
    …and even if we assume a simultaneous start, each thread has its own timeline, all of them being concurrent, but not necessarily parallel, so whatever someone assumes about the simultaneity of threads can (will) be void in the next nanosecond (of whichever timeline)…
    – Holger
    Nov 21, 2017 at 9:40
-1

I've checked proposed answers and I've noticed that using classic spin locks works better when starting threads at the "same moment" and success rate for threads collisions is better.

AtomicInteger startedThreadsCount = new AtomicInteger(0);
AtomicBoolean spinLock = new AtomicBoolean(true);


void collide(Runnable runnable) {

    for (int i = 0; i < threadsCount; i++) {
      executor.execute(() -> decorate(runnable));
    }

    while (startedThreadsCount.get() < threadsCount)
      ;

    spinLock.set(false);
}

void decorate(Runnable runnable) {

    startedThreadsCount.incrementAndGet();

    while (startedThreadsCount.get() < threadsCount)
      ;

    while (spinLock.get())
      ;

     runnable.run();
  }

I've created threads-collider library which tries to run threads at "exactly" the same time to expose concurrency issues e.g. in simple unit testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.