public void sync() {
final Object object1 = new Object();
final Object object2 = new Object();
Executor executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
synchronized (object1) {
System.out.println("线程1 获取锁1");
ThreadUtils.sleep(1000);
synchronized (object2) {
System.out.println("线程1 获取锁2");
}
}
}
});
executor.execute(new Runnable() {
public void run() {
synchronized (object2) {
System.out.println("线程2 获取锁2");
synchronized (object1) {
System.out.println("线程2 获取锁1");
}
}
}
});
}
程序输入结果
线程1 获取锁1
线程2 获取锁2
通过jconsole查看 线程 并可以检查已经发生死锁