by BehindJava

What is Synchronized in Java MultiThreading

Home » java » What is Synchronized in Java MultiThreading

In this tutorial we are going to learn to learn about Synchronized in Java MultiThreading

The Process of executing two or more threads simultaneously.

To understand the Synchronized keyword better we need to know more about the Race condition.
We have int x=10 and looping it 10 times incrementing the x each time. In this case lets say we have two threads executing this block of code. When we run the same program multiple times result becomes inconsistent because two threads might be reading the same value and incrementing the x.

int x=10;
for(int i=0;i<10;i++){
//Read the value of x
//Add 1  to this value
//Store this value back to x


  • Allows only a single thread at a time to access the shared resource, and forces all other threads to wait for that accessing thread to release its access to the shared resource.
  • Each object in Java has a unique lock.
  • Applied on methods/blocks.
  • Occurs on an object. Only one thread can execute a synchronized method/block at a time for any given single object.
  • Mutual exclusion(Obtaining lock on the shared resource).

Now the issue is resolved by adding synchronized keyword to the run method which makes the result consistent.
When we use synchronized to the run method t1 object gets the lock to the run method and once its execution is completed, lock is released and t2 obtains the lock on run method.

public class RaceCondition implements Runnable {

	private int counter;

	public synchronized void run() {
		for (int i = 0; i < 5; i++) {

			try {
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block

	public int getCounter() {
		return counter;

	public static void main(String args[]) {

		RaceCondition rc = new RaceCondition();

		Thread t1 = new Thread(rc);

		Thread t2 = new Thread(rc);

		try {
		} catch (InterruptedException e1) {

		System.out.println("Counter value:" + rc.getCounter());


Counter value:10