Since multiple threads run independently without any communication between them, some problems may arise because of this asynchronous behavior of threads. Sometimes, we need an operation to be performed by only one thread at a time. Performing the same task by two threads simultaneously may lead to inconsistent results. So to ensure that two thread don’t execute the conflicting operations together and to initiate communication among thread, a process called synchronization is used.
For synchronization, Java implements: the monitor (also called a semaphore). The monitor is a control mechanism first defined by C.A.R. Hoare. A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can enter 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 have to waiting for the monitor. Hence, a monitor can be used to protect a shared process from being manipulated by more than one thread at a time.
Most multithreaded systems use monitors as objects that the program must explicitly acquire and manipulate. Each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called. 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.
Syntax :
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor.
class resource { public synchronized void disp(String id,String[] h) { for(int i=0;i<h.length;++i) { System.out.println(id+":"+h[i]); } } } class SynchronizationThread extends Thread { String s[]={"Welcome","to","Java","Programming"}; resource r; String name; SynchronizationThread(String n,resource x) { super(n); name=n; this.r=x; System.out.println("Thread is:"+getName()); } public void run() { r.disp(name,s); } } class SynchronizationJavaExample { public static void main(String args[]) { resource m=new resource(); SynchronizationThread t1=new SynchronizationThread("First Thread",m); SynchronizationThread t2=new SynchronizationThread("Second Thread",m); t1.start(); t2.start(); } }