Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 929
figaro Avatar asked Jul 31 '10 02:07

figaro


People also ask

Can two threads of a process run at the same time?

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.

Can two threads run at the same time on a single core?

If the threads were executed on more than one CPU core then they can be executed at the same time which means they are executed in parallel. In summary, multiple threads on a single CPU core can be executed concurrently.

How do you make 2 threads run one after another?

We can use use join() method of thread class. To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2. join, and T2 calls T1.


1 Answers

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.

like image 198
Enno Shioji Avatar answered Sep 22 '22 17:09

Enno Shioji