Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a piece of code only after all threads are done

I have a logging code which needs to be executed after all Threadss are executed.

Thread t1 = new MyThread();
Thread t2 = new MyThread();
t1.run();
t2.run();

doLogging();

Is there any way to execute doLogging() only after both threads are done with their processing. Now that doLogging() is called as soon as t1 and t2 are started.

like image 245
shafi Avatar asked Sep 29 '09 11:09

shafi


2 Answers

Just join() all threads before your doLogging() call:

t1.join();
t2.join();

// the following line will be executed when both threads are done
doLogging();

Note that the order of join() calls doesn't matter if you want to wait for all of your threads.

like image 66
Joachim Sauer Avatar answered Sep 20 '22 06:09

Joachim Sauer


In addition to the join() solution there is also something called CountDownLatch in the java.util.concurrent library. It allows you to initialize it to a certain number and then wait until it was hit the specified number of times.

Simple example:

CountDownLatch latch = new CountDownLatch(NUMBER_OF_THREADS);
for(int i=0; i<NUMBER_OF_THREADS;i++)
   new Thread(myCode).start();

latch.await();

The latch must be explicitly hit by the worker threads for this to work though:

latch.countDown()
like image 39
Gregory Mostizky Avatar answered Sep 23 '22 06:09

Gregory Mostizky