synchronized嵌套锁
时间: 2024-01-02 16:21:45 浏览: 71
在Java中,synchronized嵌套锁是指在一个synchronized块中,又嵌套了另一个synchronized块。这种情况下,如果不注意锁的顺序,就可能会导致死锁的问题。下面是一个简单的例子:
```java
public class DeadlockExample {
private static Object lock1 = new Object();
private static Object lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
});
t1.start();
t2.start();
}
}
```
在上面的例子中,两个线程分别获取了lock1和lock2,但是它们的获取顺序不同,这就导致了死锁的问题。当t1获取了lock1并且在等待lock2时,t2获取了lock2并且在等待lock1,这样就形成了死锁。
阅读全文