Search code examples
javamultithreadingrunnable

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.


Solution

  • 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.