Friday, October 16, 2009

Code snippet to demonstrate synchronization in Java

package threadpack;

class PrintPoem
{
 //synchronized 
 public void print(String poem) throws InterruptedException
 {
  String words[] = poem.split(",");
  for(String word : words)
  {
   System.out.println(word);
   Thread.sleep(1000);
  }
 } 
}

class ReadPoem extends Thread
{
 String poem;
 PrintPoem printPoem;
 
 public ReadPoem(String poem, PrintPoem printPoem) 
 {
  this.poem = poem;
  this.printPoem = printPoem;
  this.start();
 }
 
 public void run()
 {
  synchronized (printPoem) {
   try 
   {
    printPoem.print(poem);
   } 
   catch (InterruptedException e) 
   {
    e.printStackTrace();
   }
   
  }
  
 }
}
public class SynchronizationDemo 
{
 public static void main(String[] args) 
 {
  PrintPoem pObject = new PrintPoem();
  new ReadPoem("Twinkle,Twinkle,Little,Star",pObject);
  new ReadPoem("Johny,Johny,Yes,Papa",pObject);
  
 }

}

No comments:

Post a Comment