Hey friends a simple code for thread synchronization in Java is shown below:
Thread.java
class Show {
 synchronized public void display(String s)
 {
   System.out.print("Hello "+s);
   try{
   Thread.sleep(100);
   }
   catch(Exception e){}
   System.out.println(" Welcome");
 }
}
class A extends Thread {
 Show s;
 String msg;
 public A(String m,Show obj)
 {
  s=obj;
  msg=m;
 }
 public void run()
 {
   s.display(msg);
 }
}
class Threadsyn {
 public static void main(String args[])
 {
  Show s=new Show();
  A a1= new A("Ram",s);
  A a2= new A("Rohit",s);
  A a3= new A("Raj",s);  
  a1.start();
  a2.start();
  a3.start();
 }
}
Have Funs..............

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.