Synchronization

When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. As you will see, Java provides unique, language-level support for it. Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.

Using Synchronized Methods

Synchronization is easy in Java, because all objects have their own implicit monitor associated with them. To enter an object’s monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method. Example as follows :

class TwoStrings1 {
	synchronized static void print(String str1, String str2) {
		System.out.print(str1);
		try {
			Thread.sleep(1000);
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
		System.out.println(str2);
	}
}

class PrintStringsThread1 implements Runnable {
	String str1, str2;

	PrintStringsThread1(String str1, String str2) {
		this.str1 = str1;
		this.str2 = str2;
		new Thread(this).start();
	}

	public void run() {
		TwoStrings1.print(str1, str2);
	}
}

public class Sync {
	public static void main(String args[]) {
		new PrintStringsThread1("Hello ", "there.");
		new PrintStringsThread1("How are ", "you?");
		new PrintStringsThread1("Thank you ", "very much!");
	}
}