7

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.

God
  • 1,238
  • 2
  • 18
  • 45
shafi
  • 801
  • 1
  • 7
  • 6
  • 3
    It should be pointed out that since you are calling run instead of start you're already getting the desired behavior. –  Sep 29 '09 at 12:56

3 Answers3

24

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • Note that if you're using Java 1.5 or later the new java.util.concurrent should be preferred over low-level thread programming (see Gregory Mostizky's answer). – Jim Ferrans Nov 29 '09 at 16:39
  • @Jim: with Java 1.5 or later I wouldn't even use a CountDownLatch for such a thing, but a simple Executor. – Joachim Sauer Nov 29 '09 at 17:51
6

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()
Gregory Mostizky
  • 7,231
  • 1
  • 26
  • 29
0

If you create threads using a thread pool, then you may use awaitTermination(long timeout, TimeUnit unit) method. Once time up, it will return true if all threads are finished, otherwise return false.

if(awaitTermination(timeout, unit)){
    //write your code here
}

However, since you need to estimate a timeout first, it's not as flexible as CountDownLatch. This method is usually used together with shutdown() to double-check if all threads are shut down successfully given a waiting time.

Alex
  • 601
  • 8
  • 22