Master java skills

Synchronized methods

On the previous page, we learnt how to synchronize run() method and why it fails to snynchronize if we use different objects of Runnable type class.

In this tutorial, we will synchronize a normal method of a class which is invoked from inside run() method of the class that implements Runnable interface.

Number.java whose method displayNumbers () is synchronized.

package com.javatrainingschool;

public class Number {

	public synchronized void displayNumbers() {
		for(int i=0; i<5; i++)
			System.out.println(Thread.currentThread().getName() + " : " + i);
	}	
}
package com.javatrainingschool;

public class SynchronizedMethodExample implements Runnable {

	Number number;
	
	public SynchronizedMethodExample(Number number) {
		super();
		this.number = number;
	}
	
	@Override
	public void run() {
		number.displayNumbers();
	}
	
	public static void main(String[] args) {

//note that we have one object of the class Number whose method is synchronized. The same object is being shared between the 3 threads
		Number number = new Number();
		Runnable rt1 = new SynchronizedMethodExample(number);
		Runnable rt2 = new SynchronizedMethodExample(number);
		Runnable rt3 = new SynchronizedMethodExample(number);
		Thread t1 = new Thread(rt1, "thread-a");
		Thread t2 = new Thread(rt2, "thread-b");
		Thread t3 = new Thread(rt3, "thread-c");
		
		t1.start();
		t2.start();
		t3.start();
			
	}
	
}
Output :
thread-a : 0
thread-a : 1
thread-a : 2
thread-a : 3
thread-a : 4
thread-c : 0
thread-c : 1
thread-c : 2
thread-c : 3
thread-c : 4
thread-b : 0
thread-b : 1
thread-b : 2
thread-b : 3
thread-b : 4

Synchronized method example

Let’s understand one more synchronized method example

package com.javatrainingschool;

public class Calculation {

	public synchronized void sum(int i) {
		System.out.println(Thread.currentThread().getName() + " : sum = " + (i + i));
	}
	
	public synchronized void square(int j) {
		System.out.println(Thread.currentThread().getName() + " : square = " + j*j);
	}
}
package com.javatrainingschool;

public class SynchronizedMethodExample implements Runnable {

	Calculation calculation;
	
	public SynchronizedMethodExample(Calculation calculation) {
		super();
		this.calculation = calculation;
	}
	
	@Override
	public void run() {
		calculation.sum(4);
		calculation.square(6);
	}
	
	public static void main(String[] args) {
		Calculation calculation = new Calculation();
		Runnable rt1 = new SynchronizedMethodExample(calculation);
		Runnable rt2 = new SynchronizedMethodExample(calculation);
		Runnable rt3 = new SynchronizedMethodExample(calculation);
		Thread t1 = new Thread(rt1, "thread-a");
		Thread t2 = new Thread(rt2, "thread-b");
		Thread t3 = new Thread(rt3, "thread-c");
		
		t1.start();
		t2.start();
		t3.start();
			
	}
	
}
Output :
thread-a : sum = 8
thread-c : sum = 8
thread-c : square = 36
thread-b : sum = 8
thread-b : square = 36
thread-a : square = 36