两个线程,假设第一个线程先执行了execute1拿到lock1 锁标记,sleep,让出cpu时间片;第二个线程 拿到lock2。此时线程1尝试拿lock2 始终拿不到,线程2也是如此,所以进入死锁状态。
public class DemoThread12 {
private Object lock1 = new Object();
private Object lock2 = new Object();
public void execute1() {
synchronized (lock1) {
System.out.println("线程" + Thread.currentThread().getName() + "获得lock1执行execute1开始");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("线程" + Thread.currentThread().getName() + "获得lock2执行execute1开始");
}
}
}
public void execute2() {
synchronized (lock2) {
System.out.println("线程" + Thread.currentThread().getName() + "获得lock2执行execute2开始");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("线程" + Thread.currentThread().getName() + "获得lock1执行execute2开始");
}
}
}
public static void main(String[] args) {
final DemoThread12 demo = new DemoThread12();
new Thread(new Runnable() {
@Override
public void run() {
demo.execute1();
}
}, "t1").start();
new Thread(new Runnable() {
@Override
public void run() {
demo.execute2();
}
}, "t2").start();
}
}