Search This Blog

Thursday, 16 March 2017

Program in JAVA to implement Mutual Exclusion.

public class Counter_locks implements Runnable {

      int count = 0;

     public Counter_locks() { 
     }

     public synchronized void run()  //synchronizes the run method
     {
         System.out.println(Thread.currentThread().getName() + ": " + "Current Value of count = " + count);
         System.out.println(Thread.currentThread().getName() + " increments count....");
         count ++;
        try {
                             Thread.currentThread().sleep(1000);
         } catch (InterruptedException e) {
             System.out.println("Thread " + Thread.currentThread().getName() + "interrupted.");
         }
         System.out.println("Value of count after incremented by thread "
         + Thread.currentThread().getName() + " = " + count);
     }

     public static void main(String args[]) {
         Counter_locks c = new Counter_locks();
  
         Thread t1 = new Thread(c);
         Thread t2 = new Thread(c);
         Thread t3 = new Thread(c);
         Thread t4 = new Thread(c);
  
         t1.setName("Thread 1");
         t2.setName("Thread 2");
         t3.setName("Thread 3");
         t4.setName("Thread 4");
  
         t1.start();
         t2.start();
         t3.start();
         t4.start();
  
         try {
             t1.join();
             t2.join();
             t3.join();
             t4.join();
         }
         catch (InterruptedException e) {
             System.out.println("Main thread Interrupted .....");
         }
  
         System.out.println("Main thread exits.....");
     }
 }

Output :

D:\>javac  Counter_locks.java
D:\>java Counter_locks
Thread 1: Current Value of count = 0
Thread 1 increments count....
Value of count after incremented by thread Thread 1 = 1
Thread 4: Current Value of count = 1
Thread 4 increments count....
Value of count after incremented by thread Thread 4 = 2
Thread 3: Current Value of count = 2
Thread 3 increments count....
Value of count after incremented by thread Thread 3 = 3
Thread 2: Current Value of count = 3
Thread 2 increments count....
Value of count after incremented by thread Thread 2 = 4

Main thread exits.....

No comments:

Post a Comment