Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate synchronized method.

Java Code Example — Multithreading Programs

ADVERTISEMENT

Java Program to demonstrate synchronized method.

Objective

Write a Java program to demonstrate thread synchronization using a Synchronized Method.

Algorithm / Approach

  1. Create a Table class with a method table(int x) that prints the multiplication table for x with a small sleep delay.
  2. Add the synchronized keyword to the table() method signature.
  3. Create two different thread classes (Thread1 and Thread2) that both share the SAME Table object and call its method.
  4. 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 synchronized keyword to the method, we lock the object. When Thread1 enters the table() 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)
ADVERTISEMENT