How to execute part of the code only after completion of all threads

I have a registration code that needs to be executed after all Threads .

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

Is there a way to doLogging() only after both threads have been processed. Now that doLogging() is called as soon as t1 and t2 begin.

+6
java multithreading runnable
source share
3 answers

Just join() all threads before calling doLogging() :

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

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

+19
source share

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

A 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 capture must be clearly hit by workflows in order for this to work:

 latch.countDown() 
+6
source share

If you use code from the main thread, keep in mind that this will cause the user interface to hang until both threads are complete. This may not be the desired effect.

Instead, you can consider a construct in which each thread synchronizes over your Logger object and makes calls to it inside that construct. Since I don’t know what you are specifically trying to achieve, another solution is what Joachim suggested, only putting this code in a stream.

0
source share

All Articles