Search Here

Java program for Synchronizing a Method


/* Synchronized Method */
class Display
{  
 synchronized void display(int n)
 {  
  for(int i=0;i<5;i++)
  {  
   System.out.println((n+i));  
   try
   {  
    Thread.sleep(50);  
   }
   catch(Exception e)
   {
    System.out.println(e);
   } 
  }    
 }  
}  
  
class Thread_1 extends Thread
{  
 Display t;  
 Thread_1(Display t)
 {  
  this.t=t;  
 }  
 public void run()
 {  
  t.display(1);  
 }  
}  
class Thread_2 extends Thread
{  
 Display t;  
 Thread_2(Display t)
 {  
  this.t=t;  
 }   
 public void run()
 {  
  t.display(6);  
 }  
}  
  
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);  
  t1.start();  
  t2.start();  
 }  
}

JAVA program for synchronizing a method
Output

No comments:

Post a Comment