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]

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative