- 常見情形之一,同步的嵌套。
- 開發中盡量不發生,但考試時可能遇到。
public class DeadLockTest2 {
public static final Object LOCK_A = new Object();//定義兩個鎖(對象)
public static final Object LOCK_B = new Object();
}
public class DeadLockTest1 implements Runnable {
private boolean flag;
DeadLockTest1(boolean flag) {
this.flag = flag;
}
public void run() {
if(flag) {
while(true) {//嘗試直到鎖上為止
synchronized(DeadLockTest2.LOCK_A) {
System.out.println(Thread.currentThread().getName() + " @ if @ LOCKA");
synchronized(DeadLockTest2.LOCK_B) {
System.out.println(Thread.currentThread().getName() + " @ if @ LOCK_B");
}
}
}
} else {
while(true) {//嘗試直到鎖上為止
synchronized(DeadLockTest2.LOCK_B) {
System.out.println(Thread.currentThread().getName() + " @ else @ LOCK_B");
synchronized(DeadLockTest2.LOCK_A) {
System.out.println(Thread.currentThread().getName() + " @ else @ LOCK_A");
}
}
}
}
}
}
public class DeadLockTest {
public static void main(String[] args) {
DeadLockTest1 a = new DeadLockTest1(true);
DeadLockTest1 b = new DeadLockTest1(false);
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
t1.start();
t2.start();
}
}
打印結果
Thread-1 @ else @ LOCK_B
Thread-0 @ if @ LOCKA
//鎖不上的狀態
public class DeadLock implements Runnable {
private int num = 10;
Object obj = new Object();//創建對象傳入同步代碼塊
boolean flag = true;
public void run() {
if(flag) {
while(true) {
synchronized(obj) {//簡單來講,相當於一道鎖(同步鎖),讓其他線程進不來
show();
}
}
} else {
while(true) {
this.show();//同步函數
}
}
}
public synchronized void show() {
synchronized(obj) {
if(num > 0) {
try {
Thread.sleep(10);//暫停十毫秒
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + " sale " + num--);
}
}
}
}
public class DeadLockDemo {
public static void main(String[] args) {
DeadLock d = new DeadLock();//創建一個線程任務對象
Thread d1 = new Thread(d);
Thread d2 = new Thread(d);
d1.start();
try {
Thread.sleep(10);//主函數暫停十毫秒
} catch (InterruptedException e) {
}
d.flag = false;//讓 t2 讀 else 語句
d2.start();
}
}
打印結果
Thread-0 sale 10
//鎖不上的狀態