Search Here

Java program for creating Deadlock


/* Deadlock Occurence */

class Display
{  
 synchronized void display1()
 {  
  for(int i=1;i<=5;i++) 
   System.out.println((i));  
 }

 synchronized void display2()
 {  
  for(int i=6;i<=15;i++) 
   System.out.println((i));  
 }
}  
  
class Thread_1 extends Thread
{  
 Display t;  
 Thread_1(Display t)
 {  
  this.t=t;  
 }  
 public void run()
 {  
  t.display1();
  System.out.println("Thread_1 is waiting for display2 ...");
  suspend();
  t.display2();
  
  System.out.println("Exiting Thread_1");
 }  
}  

class Thread_2 extends Thread
{  
 Display t;  
 Thread_2(Display t)
 {  
  this.t=t;  
 }   
 public void run()
 {  
  t.display2();
  System.out.println("Thread_2 is waiting for display1 ...");
  suspend();
  t.display1();
  System.out.println("Exiting Thread_2");
 }  
}  
  
class Main
{  
 public static void main(String args[]) 
 {  
  Display obj = new Display();
  Thread_1 t1=new Thread_1(obj);  
  Thread_2 t2=new Thread_2(obj);  
  
  System.out.println("Starting Thread_1");
  t1.start();  
  System.out.println("Starting Thread_1");
  t2.start();  
  
  System.out.println("Exiting main thread");
 }  
}

No comments:

Post a Comment