sandeshMC

Mutual Exclusion with static Lock object!

Apr 27th, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.89 KB | None | 0 0
  1. //Mutual Exclusion
  2.  
  3. import java.util.concurrent.locks.*;
  4.  
  5. public class ThreadDemo extends Thread {
  6.  
  7.     int threadNo;
  8.     static Lock lock = new ReentrantLock();
  9.  
  10.     ThreadDemo(int x) {
  11.         this.threadNo = x;
  12.     }
  13.  
  14.     @Override
  15.     public synchronized void run() {
  16.         lock.lock();
  17.         try {
  18.             System.out.println("Thread " + threadNo + " entered the critical section.");
  19.             System.out.println("Thread " + threadNo + " out of the critical section.");
  20.  
  21.         } finally {
  22.             lock.unlock();
  23.         }
  24.     }
  25.  
  26.     public static void main(String argsp[]) throws InterruptedException {
  27.         ThreadDemo t1 = new ThreadDemo(1);
  28.         ThreadDemo t2 = new ThreadDemo(2);
  29.         ThreadDemo t3 = new ThreadDemo(3);
  30.         t1.start();
  31.         t2.start();
  32.         t3.start();
  33.         t1.join();
  34.         t2.join();
  35.         t3.join();
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment