Java Program to demonstrate synchronized method.
Objective
Write a Java program to demonstrate thread synchronization using a Synchronized Method.
Algorithm / Approach
- Create a
Tableclass with a methodtable(int x)that prints the multiplication table forxwith a small sleep delay. - Add the
synchronizedkeyword to thetable()method signature. - Create two different thread classes (
Thread1andThread2) that both share the SAMETableobject and call its method. - Start both threads.
Table.java
class Table {
synchronized void table(int x) {
for(int i = 1; i<=10; i++) {
System.out.println(x*i);
try{
Thread.sleep(400);
}
catch(Exception e){
System.out.println(e);
}
}
}
}
class Thread1 extends Thread {
Table t;
Thread1(Table t){
this.t = t;
}
public void run() {
t.table(10);
}
}
class Thread2 extends Thread {
Table t;
Thread2(Table t) {
this.t = t;
}
public void run() {
t.table(2);
}
}
class Test {
public static void main(String[] a)
{
Table t = new Table();
Thread1 th1 = new Thread1(t);
Thread2 th2 = new Thread2(t);
th1.start();
th2.start();
}
}
Expected Output
10 20 30 40 50 60 70 80 90 100 2 4 6 8 10 12 14 16 18 20
Explanation of the Program
- When multiple threads try to access and modify the same shared resource simultaneously, it causes data inconsistency (a Race Condition).
- By adding the
synchronizedkeyword to the method, we lock the object. When Thread1 enters thetable()method, it takes the lock. Thread2 is forced to wait outside until Thread1 completely finishes the multiplication table and releases the lock. - This guarantees that the table of 10 prints entirely before the table of 2 begins, rather than the numbers mixing together randomly.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)