facebook twitter youtube
by Amit Gupta - no comments

I prefer not to go theory. So lets start practical


Statement 1
Statement 2

  1. If Statement 1 is a thread statement then Statement 2 can be executed any time. It doesn’t wait Statement 1 to be completed.
  2. If Statement 1 is simple statement then Statement 2 can’t be executed until Statement 1 is completed.
  3. If Statement 1 is a thread statement calling join() then Statement 2 can’t be executed until Statement 1 is completed.
  4. If Statement 1 is a thread statement calling join(n) then Statement 2 can’t be executed until Statement 1 is completed or time n is over.

Study with program

package Simple;

public class JoinDemo extends Object {
	  public static Thread createThread(String name, long napTime) {
	    final long sleepTime = napTime;

	    Runnable r = new Runnable() {
	        public void run() {
	          try {
	            print("in run() - entering");
	            Thread.sleep(sleepTime);
	          } catch ( InterruptedException x ) {
	            print("interrupted!");
	          } finally {
	            print("in run() - leaving");
	          }
	        }
	      };
	  
	    Thread t = new Thread(r, name);
	    t.start();

	    return t;
	  }

	  private static void print(String msg) {
	    String name = Thread.currentThread().getName();
	    System.out.println(name + ": " + msg);
	  }

	  public static void main(String[] args) throws Exception{
	    Thread[] t = new Thread[2];
	    t[0] = createThread("thread A", 2000);
	    //t[0].join();
	    t[1] = createThread("thread B", 1000);
	    	    
	  }
	}

Explanation:

When createThread() get called it creates a thread. Thread.sleep() interrupts this thread. So another createThread() call takes place.

    t[0] = createThread("thread A", 2000); //statement 1
    t[1] = createThread("thread B", 1000); //statement 3

Output:
thread A: in run() – entering
thread B: in run() – entering
thread B: in run() – leaving
thread A: in run() – leaving

    t[0] = createThread("thread A", 2000); //statement 1
    t[0].join();                           //statement 2
    t[1] = createThread("thread B", 1000); //statement 3

Output
thread A: in run() – entering
thread A: in run() – leaving
thread B: in run() – entering
thread B: in run() – leaving

In above condition, first t[0] will be completed then statement 3 will be called.

Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

Leave a Reply

captcha