Thread join()

public class ThreadJoinEx {

  public static void main(String[] args) throws InterruptedException {
    ThreadJoinEx tjEx = new ThreadJoinEx();
    out.println(threadName() + "starting" + sec());
    Thread sleepingThread = tjEx.createSleeping(5);
    sleepingThread.start();
    sleepingThread.join();
    out.println(threadName() + "finished" + sec());
  }

  Thread createSleeping(final int limit) {
    return new Thread(new Runnable() {

      @Override
      public void run() {
        for (int i = limit; i > 0; i--) {
          out.println(threadName()+"sleep,"+i+sec());
          sleepSeconds(1);
        }
      }
    });
  }

  static String threadName() {
    return Thread.currentThread().getName() + ",";
  }

  static void sleepSeconds(int n) {
    try {
      Thread.sleep(1000 * n);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  static String sec() {
    long currentTimeMillis = currentTimeMillis();
    long value = currentTimeMillis / 1000;
    return ",second " + (value - (value / 100 * 100));
  }

}

Result:

// started main thread
main,starting,second 0

// started sleeping thread

Thread-0,sleep,5,second 0
Thread-0,sleep,4,second 1
Thread-0,sleep,3,second 2
Thread-0,sleep,2,second 3
Thread-0,sleep,1,second 4

// sleeping thread finished
// main thread finished
main,finished,second 5

Main thread will wait till sleeping thread completes before main finishes sleepingThread.join();.

If we omit call to sleepingThread.join() then the main thread would finish immediately, the sleepingThread would continue to run:

main,starting,second 0
Thread-0,sleep,5,second 0
main,finished,second 0
Thread-0,sleep,4,second 1
Thread-0,sleep,3,second 2
Thread-0,sleep,2,second 3
Thread-0,sleep,1,second 4

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s