Tuesday, December 2, 2014

Write a program for deadlock


class Resource1 extends Thread {
  public void run() {
    System.out.println("Resource1" + getName());
    synchronized (Resource1.class) {
      try {
        Thread.sleep(10);
      }
      catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (Resource2.class) {
      }
    }
  }
}
class Resource2 extends Thread {
  public void run() {
    System.out.println("Resource2" + getName());
    synchronized (Resource2.class) {
      try {
        Thread.sleep(10);
      }
      catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (Resource1.class) {
      }
    }
  }
}
public class Deadlock_example {
  public static void main(String[] args) {
    Resource1 r1 = new Resource1();
    Resource2 r2 = new Resource2();
    r1.start();
    r2.start();
  }
}

No comments:

Post a Comment