Advertisement
sandeshMC

Mutual Exclusion!

Apr 27th, 2015
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.82 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.     Lock lock = new ReentrantLock();
  9.  
  10.     ThreadDemo(int x) {
  11.         this.threadNo = x;
  12.     }
  13.  
  14.     @Override
  15.     public void run() {
  16.         try {
  17.             lock.lock();
  18.             System.out.println("Thread " + threadNo + " entered the critical section.");
  19.             System.out.println("Thread " + threadNo + " out of the critical section.");
  20.         } finally {
  21.             lock.unlock();
  22.         }
  23.     }
  24.  
  25.     public static void main(String argsp[]) throws InterruptedException {
  26.         ThreadDemo t1 = new ThreadDemo(1);
  27.         ThreadDemo t2 = new ThreadDemo(2);
  28.         ThreadDemo t3 = new ThreadDemo(3);
  29.         t1.start();
  30.         t2.start();
  31.         t3.start();
  32.  
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement