Java Thread deadlock

Introduction

Deadlock occurs when two threads have a circular dependency on a pair of synchronized objects.


// An example of deadlock.
class Worker1 {//from w  w w  .  ja  v  a2  s.c o  m
  synchronized void work(Worker2 worker2) {
    String name = Thread.currentThread().getName();

    System.out.println(name + " entered A.foo");

    try {
      Thread.sleep(1000);
    } catch(Exception e) {
      System.out.println("A Interrupted");
    }

    System.out.println(name + " trying to call B.last()");
    worker2.last();
  }

  synchronized void last() {
    System.out.println("Inside A.last");
  }
}

class Worker2 {
  synchronized void work(Worker1 worker1) {
    String name = Thread.currentThread().getName();
    System.out.println(name + " entered B.bar");

    try {
      Thread.sleep(1000);
    } catch(Exception e) {
      System.out.println("B Interrupted");
    }

    System.out.println(name + " trying to call A.last()");
    worker1.last();
  }

  synchronized void last() {
    System.out.println("Inside A.last");
  }
}

class Deadlock implements Runnable {
  Worker1 worker1 = new Worker1();
  Worker2 worker2 = new Worker2();

  Deadlock() {
    Thread.currentThread().setName("MainThread");
    Thread t = new Thread(this, "RacingThread");
    t.start();

    worker1.work(worker2); // get lock on a in this thread.
    System.out.println("Back in main thread");
  }

  public void run() {
    worker2.work(worker1); // get lock on b in other thread.
    System.out.println("Back in other thread");
  }

  public static void main(String args[]) {
    new Deadlock();
  }
}
class MyThread extends Thread {
   String r1, r2;//from ww w. jav  a2  s .  c o m
   int id;

   MyThread(int i, String s1, String s2) {
      id = i;
      r1 = s1;
      r2 = s2;
      start();
   }

   public void run() {
      synchronized (r1) {
         System.out.println("Thread " + id + " obtained a lock on " + r1);
         try {
            Thread.sleep(1000);
         } catch (Exception e) {
         }
         System.out.println("Thread " + id + " is waiting to obtain a lock on " + r2);
         synchronized (r2) {
            System.out.println("Thread " + id + " obtained a lock on " + r2);
         }
      }
   }
}

public class Main {
   public static void main(String args[]) throws Exception {
      int a[] = { 2, 6, 4, 0, 1, 5, 3 };
      String r1 = new String("R1"), r2 = new String("R2");
      MyThread t1 = new MyThread(1, r1, r2);
      MyThread t2 = new MyThread(2, r2, r1);
   }
}



PreviousNext

Related