Multithreading Example with Synchronization

In this article, we will learn about Multithreading Example with Synchronization.
Here is the same example that prints the counter’s value one by one and gives the same result every time we run it.

Example

In the below code we have the printCount() function where we are printing the values. Also, we are checking from where the thread starts and ends.

class PrintExample {
   public void printCount() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Counter:"  + i );
         }
      } catch (Exception e) {
         System.out.println("Thread interrupted");
      }
   }
}

class ThreadExample extends Thread {
   private Thread t;
   private String threadName;
   PrintDemo  PD;

   ThreadExample( String name,  PrintExample pd) {
      threadName = name;
      PD = pd;
   }
   
   public void run() {
      synchronized(PD) {
         PD.printCount();
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }

   public void start () {
      System.out.println("Starting the" +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThreadExample {

   public static void main(String args[]) {
      PrintExample PD = new PrintExample();

      ThreadExample T1 = new ThreadExample( "Thread - 1 ", PD );
      ThreadExample T2 = new ThreadExample( "Thread - 2 ", PD );
      T1.start();
      T2.start();
      try {
         T1.join();
         T2.join();
      } catch ( Exception e) {
         System.out.println("Interrupted");
      }
   }
}

Output

Starting the Thread - 1
Starting the Thread - 2
Counter:   5
Counter:   4
Counter:   3
Counter:   2
Counter:   1
Thread Thread - 1  exiting.
Counter:   5
Counter:   4
Counter:   3
Counter:   2
Counter:   1
Thread Thread - 2  exiting.

That’s all, we will learn about Multithreading Example with Synchronization

Next Article

1. Thread Synchronization in Java
2. Multithreading Example without Synchronization

Please share this post:
Posts created 78

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: