思路:
創(chuàng)建兩個字符串a(chǎn)和b榆纽,再創(chuàng)建兩個線程A和B,
讓每個線程都用synchronized鎖住字符串(A先鎖a捏肢,再去鎖b奈籽;B先鎖b,再鎖a)
如果A鎖住a鸵赫,B鎖住b衣屏,A就沒辦法鎖住b,B也沒辦法鎖住a辩棒,這時就陷入了死鎖
public class DeadLock {
public static String obj1 = "obj1";
public static String obj2 = "obj2";
public static void main(String[] args){
Thread a = new Thread(new Lock1());
Thread b = new Thread(new Lock2());
a.start();
b.start();
}
}
class Lock1 implements Runnable{
@Override
public void run(){
try{
System.out.println("Lock1 running");
while(true){
synchronized(DeadLock.obj1){
System.out.println("Lock1 lock obj1");
// 獲取obj1后先等一會兒狼忱,讓Lock2有足夠的時間鎖住obj2
Thread.sleep(3000);
synchronized(DeadLock.obj2){
System.out.println("Lock1 lock obj2");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
class Lock2 implements Runnable{
@Override
public void run(){
try{
System.out.println("Lock2 running");
while(true){
synchronized(DeadLock.obj2){
System.out.println("Lock2 lock obj2");
Thread.sleep(3000);
synchronized(DeadLock.obj1){
System.out.println("Lock2 lock obj1");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
打印結(jié)果: