Monday, March 2, 2015

Join in Threads

About join, when I use join method on a thread then it waits for that particular thread to complete/die and then proceed with the other threads.Below example explains the same.

thread1.java

package Threadsexample;

public class thread1 extends Thread {
 
 public void run(){
  System.out.println("thread one");
  
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

thread2.java

package Threadsexample;

public class thread2 implements Runnable{

 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println("Thread 2");
  
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

mainclass.java

 
package Threadsexample;

public class mainclass {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Thread t=new thread1();
  Runnable r=new thread2();
  
  t.start();
  try {
   t.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  new Thread(r).start();
  System.out.println(t.getName());
 }

}


output :
thread one
Thread-0
Thread 2
>>>
------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment