Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. package ex;
  2.  
  3. public class Deadlock implements Runnable {
  4.  
  5.   public static void main(String[] args) {
  6.     Object a = "Resource A";
  7.     Object b = "Resource B";
  8.     Thread t1 = new Thread(new Deadlock(a, b));
  9.     Thread t2 = new Thread(new Deadlock(a, b));
  10.     t1.start();
  11.     t2.start();
  12.  
  13.   }
  14.   private Object firstResource;
  15.   private Object secondResource;
  16.  
  17.   public Deadlock(Object first, Object second) {
  18.     firstResource = first;
  19.     secondResource = second;
  20.  
  21.   }
  22.  
  23.   @Override
  24.   public void run() {
  25.     while (true) {
  26.       System.out.println(Thread.currentThread().getName() + " Looking for lock on " + firstResource);
  27.    
  28.     synchronized (firstResource) {
  29.       System.out.println(Thread.currentThread().getName() + " Obtained lock on " + firstResource);
  30.       System.out.println(Thread.currentThread().getName() + " Looking for lock on " + secondResource);
  31.     }
  32.     synchronized (secondResource) {
  33.       System.out.println(Thread.currentThread().getName() + " Obtained lock on " + secondResource);
  34.       try {
  35.         Thread.sleep(100);
  36.       } catch (InterruptedException e) {
  37.       }
  38.     }
  39.     }
  40.   }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement