Java Thread Synchronization – Explained With Examples

Submitted by Aman Gautam Last updated : January 26, 2024

Thread Synchronization

In Java, thread synchronization refers to the process of allowing the accessibility of an object to only one thread when multiple threads are trying to access an object at the same time.

Achieving Thread Synchronization

In the multithreaded programming, multiple threads run simultaneously and access common resources. To prevent deadlock, we must ensure that a resource must be shared by one thread at a time or else it may produce a weird or unforeseen result. This can be done by the thread synchronization which can be achieved by using the `synchronized` keyword.

Example

Let us understand this by taking an example.

There are two threads which are accessing and writing to common file output.txt. If no synchronization is used then, one thread writes few words in the file and meanwhile another thread starts writing to the file. The resulting file will contain random contents written by both threads. With synchronization, if one thread is writing to the file, the file will be locked (in LOCK mode) and no other thread or process can access it until first thread completed its work.

Code Without Thread Synchronisation

class print {
  public void printMSG(String s) {
    for (int i = 1; i <= 5; i++) {
      System.out.println(s);
      try {
        // sleep current execution for 1s
        Thread.sleep(1000); 
      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }
}

class one extends Thread {
  print t;
  one(print t) {
    this.t = t;
  }
  public void run() {
    t.printMSG("Hi");
  }
}

class two extends Thread {
  print t;
  two(print t) {
    this.t = t;
  }

  public void run() {
    t.printMSG("Bye");
  }
}

public class ExSynchronization {
  public static void main(String[] args) {
    print t = new print();
    one ob = new one(t);
    two o2 = new two(t);
    
    ob.start();
    o2.start();
  }
}

Output

Hi
Bye
Bye
Hi
Hi
Bye
Hi
Bye
Hi
Bye

Note: This output is random.

In this program, we have designed two thread which are accessing a common function printMSG(). When we run this code, we may get the unwanted output as seen above.

To synchronise the output we will use synchronized method. This will lock the object for a shared resource. We can do this by adding synchronized keyword to the shared method.

Code With Thread Synchronisation

class print {
  synchronized public void printMSG(String s) {
    for (int i = 1; i <= 5; i++) {
      System.out.println(s);
      try {
        // sleep current execution for 1s
        Thread.sleep(1000); 
      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }
}

class one extends Thread {
  print t;
  one(print t) {
    this.t = t;
  }
  public void run() {
    t.printMSG("Hi");
  }
}

class two extends Thread {
  print t;
  two(print t) {
    this.t = t;
  }

  public void run() {
    t.printMSG("Bye");
  }
}

public class ExSynchronization {
  public static void main(String[] args) {
    print t = new print();
    one ob = new one(t);
    two o2 = new two(t);
    
    ob.start();
    o2.start();
  }
}

Output

Hi
Hi
Hi
Hi
Hi
Bye
Bye
Bye
Bye
Bye

Note: The threads may start in either order.


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.