Wednesday, November 7, 2012

Java thread synchronization

Here is a small example of thread synchronization in Java

File: Message.java

package com.giri.threads;

public class Message {
 
 public Message() {
  // nothing
 }
 
 public void print(String msg) {
  System.out.println("\n[Message] " + msg);
 
  try {
   Thread.sleep(1000);
  } catch(Exception e) {
   e.printStackTrace();
  }
 }
}

File: SynchronizedThread .java

package com.giri.threads;

public class SynchronizedThread implements Runnable {
 
 private String str;
 private Message message;
 private Thread t;
 
 public SynchronizedThread(Message m, String s) {
  message = m;
  str = s;
  t = new Thread(this);
  t.start();
 }
 
 // synchronized calls to print()
 @Override
 public void run() {
  synchronized(message) {
   message.print("This is from SynchronizedThread: run(): "+str);
  }
 }
}

File: MainClass.java

package com.giri.threads;

public class MainClass {

 private static Message msg = new Message();
 
 private static Thread st1 = new Thread(new SynchronizedThread(msg, "Hello"));
 private static Thread st2 = new Thread(new SynchronizedThread(msg, "This is a test of"));
 private static Thread st3 = new Thread(new SynchronizedThread(msg, "Synchronization"));
 private static Thread st4 = new Thread(new SynchronizedThread(msg, "in Java"));
 
 public static void main(String[] args) {
  try {
   st1.join();
   st2.join();
   st3.join();
   st4.join();
  } catch(Exception e) {
   e.printStackTrace();
  }
 }

}

Output


[Message] This is from SynchronizedThread: run(): Hello

[Message] This is from SynchronizedThread: run(): in Java

[Message] This is from SynchronizedThread: run(): Synchronization

[Message] This is from SynchronizedThread: run(): This is a test of

No comments :

Post a Comment