Synchronized methods
When a method in Java needs to be synchronized, the keyword synchronized should be added.
Example:
Public synchronized void increment()
{
X++;
}
Synchronization does not allow invocation of this Synchronized method for the same object until the first thread is done with the object. Synchronization allows having control over the data in the class.
Synchronized Statement:
A synchronized Statement can only be executed once the thread has obtained a lock for the object or the class that has been referred to in the statement. Synchronized statement contains a synchronized block, within which is placed objects and methods that are to be synchronized.
Example:
public void run()
{
synchronized(p1)
{
//synchronize statement. P1 here is an object of some class P
p1.display(s1);
}
}