标签:
死锁示例程序: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(); } }
运行:
可以看到两个线程一直阻塞;
查看当前锁视图:
右键导出:
可以看到线程阻塞情况的文字描述;
死锁的解锁秘籍是获取锁的顺序保持一致;
使用jprofile研究线程分配和同步以发现死锁和数据竞争问题,提高性能
标签:
原文地址:http://www.cnblogs.com/yejq/p/4501569.html