死鎖示例
由于兩個(gè)鎖對(duì)象lock1,lock2是static只存在一份,導(dǎo)致兩個(gè)線程執(zhí)行時(shí)會(huì)相互等待已經(jīng)被獲得的瑣對(duì)象,導(dǎo)致死鎖產(chǎn)生.
如果將static去掉,2個(gè)鎖對(duì)象就是線程獨(dú)有的變量,不會(huì)被別的線程發(fā)現(xiàn),因此不會(huì)產(chǎn)生死鎖.
public class DeadLock implements Runnable{
private String tag;
private static Object lock1 = new Object();
private static Object lock2 = new Object();
public void setTag(String tag){
this.tag = tag;
}
@Override
public void run() {
if(tag.equals("a")){
synchronized (lock1) {
try {
System.out.println("當(dāng)前線程 : " + Thread.currentThread().getName() + " 進(jìn)入lock1執(zhí)行");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("當(dāng)前線程 : " + Thread.currentThread().getName() + " 進(jìn)入lock2執(zhí)行");
}
}
}
if(tag.equals("b")){
synchronized (lock2) {
try {
System.out.println("當(dāng)前線程 : " + Thread.currentThread().getName() + " 進(jìn)入lock2執(zhí)行");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("當(dāng)前線程 : " + Thread.currentThread().getName() + " 進(jìn)入lock1執(zhí)行");
}
}
}
}
public static void main(String[] args) {
DeadLock d1 = new DeadLock();
d1.setTag("a");
DeadLock d2 = new DeadLock();
d2.setTag("b");
Thread t1 = new Thread(d1, "t1");
Thread t2 = new Thread(d2, "t2");
t1.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}