Tuesday, 29 November 2016

Program to demonstrate thread synchronization

This program demonstrates the use of thread synchronization. We have serialized the access to display( ) method. To restrict the access to display( ) method to only one thread at a time we need to preceed display( )'s definition with the keyword synchronized as shown below.


PROGRAM
class Sync {
 
 void display(String s) {
  System.out.print("[" + s);
  try {
   Thread.sleep(1000);
  }
  catch(InterruptedException e) {
   System.out.println("Exception");
  }
  System.out.println("]");
 }
}

class SyncTest extends Thread {
 String z = "";
 Sync x;
 Thread t;
 
 public SyncTest(Sync y, String s) {
  x = y;
  z = s;
  t = new Thread(this);
  t.start();
 }
 
 public void run() {
  x.display(z);
 }
}

public class SynchronizationDemo {

 public static void main(String[] args) {
  
  Sync s = new Sync();
  SyncTest s1 = new SyncTest(s, "Hello");
  SyncTest s2 = new SyncTest(s, "Rohit");
  SyncTest s3 = new SyncTest(s, "Good morning");
 }
}
OUTPUT
C:\>javac SynchronizationDemo.java
C:\>java SynchronizationDemo
[Hello]
[Rohit]
[Good morning]

No comments:

Post a Comment