Multithreading Example without Synchronization

In this article, we will learn about the Multithreading Example without Synchronization.

Here is a simple example that may or may not return the value of the counter in order, and each time we run it it will produce a different result depending on the CPU availability for a thread.

Example

class ExampleDemo {
   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() {
      PD.printCount();
      System.out.println("Thread " +  threadName + " is exiting ;)");
   }

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

public class Test_Thread {
   public static void main(String args[]) {

      PrintDemo PD = new ThreadExample ();

      ThreadExample T1 = new ThreadExample( "Thread - 1 ", PD );
      ThreadExample T2 = new ThreadExample( "Thread - 2 ", PD );

      T1.start();
      T2.start();

      // wait for threads to end
         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= 5
Counter= 2
Counter= 1
Counter= 4
Thread Thread - 1  exiting ;)
Counter= 3
Counter= 2
Counter= 1
Thread Thread - 2  exiting ;)

That’s all, we will learn about the Multithreading Example without Synchronization.

Next Article

Thread Synchronization in Java

Please share this post:
Posts created 77

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: