Advertisement
Guest User

Deadlocker.java

a guest
Apr 1st, 2011
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. import java.util.concurrent.Semaphore;
  2.  
  3. public class Deadlocker {
  4.  
  5.     public static void main(String[] args) {
  6.         new Thread(new Runnable() {
  7.             public void run() {
  8.                 while (true) {
  9.                     try {
  10.                         one();
  11.                         System.out.println("one");
  12.                     } catch (InterruptedException e) {}
  13.                 }
  14.             }
  15.         }).start();
  16.         new Thread(new Runnable() {
  17.             public void run() {
  18.                 while (true) {
  19.                     try {
  20.                         two();
  21.                         System.out.println("two");
  22.                     } catch (InterruptedException e) {}
  23.                 }
  24.             }
  25.         }).start();
  26.     }
  27.    
  28.     private static final Semaphore foo = new Semaphore(1);
  29.     private static final Semaphore bar = new Semaphore(1);
  30.    
  31.     private static void one() throws InterruptedException {
  32.         foo.acquire();
  33.         bar.acquire();
  34.         bar.release();
  35.         foo.release();
  36.     }
  37.    
  38.     private static void two() throws InterruptedException {
  39.         bar.acquire();
  40.         foo.acquire();
  41.         foo.release();
  42.         bar.release();
  43.     }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement