Synchronized Methods:
Synchronization is simple in Java since all objects have their own implicit monitor related with them. For enter an object's monitor, only call a method which has been changed along with the synchronized keyword. Although a thread is inside a synchronized method, all other threads in which try to call it (or any other synchronized method) on the similar instance have to wait. For 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.
To known the requirement for synchronization, let's starts with a simple instance which does not use it but should. The given program has three simple classes. A first one, Callme, has a single method named call ( ). The call ( ) method takes a String parameter known as msg. This function tries to print the msg string inside of square brackets. An interesting thing to note that is after call ( ) prints the opening bracket and the msg string, it calls Thread.Sleep (1000), that pauses the current thread for one.
The constructor of the next class, Caller, takes a reference to an example of the Callme class and a String that are stored in target and msg, correspondingly. The constructor also creates a new thread which will call this objects run ( ) method. The thread is beginning instantly. A run ( ) method of Caller calls the Call ( ) methods on the target example of Callme , passing in the msg string . At last, the Synch class starts through creating a single instance of Callme, and three instances of Caller, each along with a unique message string. The similar instance of Callme is passed to each Caller.
// This program is not synchronized.
class Callme {
void call(String m) { System.out.println("["+m);
try {
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target; Thread t;
public Caller(Callme t1, String s) {
tt=t1;
t=new Thread(this);
t.start();
}
public void run() {
tt.call(m);
}
}
class Synch {
public static void main(String a[]) {
Callme tt = new Callme();
Caller o1 = new Caller(tt,"hello");
Caller o2 = new Caller(tt,"Synchronized");
Caller o3 = new Caller(tt, "World");
// Wait for threads to end try {
o1.t.join(); o2.t.join(); o3.t.join();
}catch(InterruptedException e) {
System.out.println("Interrrupted");
}
}
}
Here is the output generated through this program:
Hello[Synchronized[World]]
]
]