Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results. So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point of time.

Java provides a way of creating threads and synchronizing their task by using synchronized blocks. Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.                                              

If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

class AThread {

synchronized void deposit(int amt) {

System.out.println("Deposit Completed with Rs. "+amt);

}

synchronized void withdraw(int amt) {

System.out.println("Withdraw Completed with Rs. "+amt);

}

}

 

public class Synchronization{

public static void main(String[] args) {

AThread obj=new AThread();

new Thread() {

public void run() { obj.deposit(15000);

}

}.start();

 

new Thread() {

public void run() { obj.withdraw(10000);

}

}.start();

 

}

}

Output

Deposit Completed with Rs. 15000

Withdraw Completed with Rs. 10000