Syncronization Methods
Syncronization Methods
Bing
In Java, synchronization is used to control the access of multiple threads to any shared resource. There are three main
synchronization methods:
1. Synchronized Block: A synchronized block in Java is synchronized on some object. All synchronized blocks
synchronized on the same object can only have one thread executed inside them at a time.
class Sender {
public void send(String msg) {
synchronized(this) {
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
}
1. Static Synchronization: Static synchronization synchronizes on the class’s Class object, not on individual instances
of the class.
All these methods are built around an internal entity known as the lock or monitor. Every object has a lock associated with
it. By convention, a thread that needs consistent access to an object’s fields has to acquire the object’s lock before accessing
them, and then release the lock when it’s done with them.