Monday, March 2, 2015

Synchronized Thread

By making a the run method of the thread synchronized then the corresponding thread is locked and it executes the other all threads and then execute this one. By using notify it release the threads.

 
thread1.java

package Threadsexample;

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

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();  
  new Thread(r).start();
  System.out.println(t.getName());
 }

}


>>>
------------------------------------------------------------------------------------------------------------