Java Program to demonstrate synchronized block.
Objective
Write a Java program to demonstrate thread synchronization using a Synchronized Block.
Algorithm / Approach
- Use the exact same setup as the previous program (a shared
Tableclass and two threads). - Remove the
synchronizedkeyword from the method signature. - Inside the method, wrap the critical loop code inside a
synchronized(this) { ... }block. - Start both threads.
Table.java
class Table {
void table(int x) {
synchronized(this) {
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
- A synchronized method locks the ENTIRE method. If the method contains 1000 lines of code but only 10 lines actually touch shared data, locking the whole method is highly inefficient and slows down the program.
- A synchronized block (
synchronized(this)) allows you to lock ONLY the specific lines of code that are critical, allowing multiple threads to safely execute the rest of the non-critical method code concurrently. - The
thiskeyword indicates that the lock should be placed on the current object instance.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)