你的位置:首页 > Java教程

[Java教程]使用jprofile研究线程分配和同步以发现死锁和数据竞争问题,提高性能


死锁示例程序:ThreadTest,这是经典的同步嵌套发生死锁的示例;

public class ThreadTest {  public static Object lock1 = new Object();  public static Object lock2 = new Object();  public static void method1() {    trace("Inside method1");    synchronized (lock1) {      trace("Method1 got lock1");      doSomething();      synchronized (lock2) {        trace("Method1 got lock2, sleeping");        doSomething();        trace("Method1 returning");      }    }  }  public static void method2() {    trace("Inside method2");    synchronized (lock2) {      trace("Method2 got lock2");      doSomething();      synchronized (lock1) {        trace("Method2 got lock1, sleeping");        doSomething();        trace("Method2 returning");      }    }  }  public static void doSomething() {    try {      Thread.sleep(5*1000);    }    catch (InterruptedException x) {      x.printStackTrace();    }    trace("Waiking up");  }  public static void trace(String msg) {    System.out.println(Thread.currentThread() + " : " + msg);  }  public static void main(String[] args) throws Exception {    new Thread(new Runnable() {      public void run() {        method1();      }    }).start();    new Thread(new Runnable() {      public void run() {        method2();      }    }).start();  }}

View Code

 

 

运行:

clip_image001

可以看到两个线程一直阻塞;

查看当前锁视图:

clip_image002

右键导出:

clip_image003

可以看到线程阻塞情况的文字描述;

clip_image004

死锁的解锁秘籍是获取锁的顺序保持一致;