06
Mar

synchronized object access

Object level synchronization in Java
=======================================

Step 1:  Create class that needs to be synchronized
=====================================================

class Sender {
	public void send(String msg) {
		System.out.println("Sending\t" + msg);
		try {
			Thread.sleep(1000);
		} catch (Exception e) {
			System.out.println("Thread  interrupted.");
		}
		System.out.println("\n" + msg + "Sent");
	}
}


Step 2: Create an implementation of Runnable/Thread which executes "send()" of above class
============================================================================================


class ThreadedSend extends Thread {
	private String msg;
	private Sender sender;

	ThreadedSend(String m, Sender obj) {
		this.msg = m;
		this.sender = obj;
	}

	public void run() {
		synchronized (sender) {
			sender.send(msg);
		}
	}
}



Step 3: Client which creates threads and executes them
========================================================

public class Client {

	public static void main(String args[]) {
		Sender snd = new Sender();
		ThreadedSend S1 = new ThreadedSend(" Hi ", snd);
		ThreadedSend S2 = new ThreadedSend(" Bye ", snd);

		// Start two threads of ThreadedSend type
		S1.start();
		S2.start();

		// wait for threads to end
		try {
			S1.join();
			S2.join();
		} catch (Exception e) {
			System.out.println("Interrupted");
		}
	}
}



Output:
Sending	 Hi 

 Hi Sent
Sending	 Bye 

 Bye Sent



Note, if the synchronized (sender) is commented, both the threads executes in parallel and output looks like as follow:

Sending	 Hi 
Sending	 Bye 

 Bye Sent

 Hi Sent