Deadlock Deadlock generating and positioning

Deadlock generation:

  1, two threads, each with a locked resource, while the other wants to get their resources.

Code Example:  

public class DeadLock {
  public static void main(String[] args) {
    Object a = new Object();
    Object b = new Object();
    new Thread(new MyThread(a,b),"A").start();
    new Thread(new MyThread(b,a),"B").start();
  }
}
class MyThread implements Runnable{
  private Object objectA;
  private Object objectB;
  public MyThread(Object objectA, Object objectB) {
    this.objectA = objectA;
    this.objectB = objectB;
  }
  @Override
  public void run() {
    synchronized (objectA){
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (objectB){
        System.out.println(Thread.currentThread().getName()+" run 。");
      }
    }
  }
}

Positioning deadlock: jconsole

Can be found from the chart, we create threads A, B are in the blocked state.

Click on "Deadlock Detection" button, you can locate places deadlock, as shown below:

 

Guess you like

Origin www.cnblogs.com/chen--biao/p/11350205.html