看scjp考題的時候,關於一道多線程題目,總是不能把它推成死鎖,鬱悶之下,一看答案,原來真的不是死鎖,可是爲什麼我老是想要把它推成死鎖呢?很明顯,是沒有學到家。所以,翻箱倒櫃查完資料之後,寫出一個死鎖Demo,來確定自己確實知道了什麼是死鎖。
public class DeadLockDemo {
public static void main(String[] args) {
final String lock1 = "LOCK1";
final String lock2 = "LOCK2";
Thread t1 = new Thread(){
public void run() {
synchronized (lock1) {
System.out.println("t1:Locking Source1");
try {
sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("t1:Locking Source2");
}
}
}
};
Thread t2 = new Thread(){
public void run(){
synchronized (lock2) {
System.out.println("t1:Locking Source1");
try {
sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("t2:Locking Source1");
}
}
}
};
t1.start();
t2.start();
}
}
/*Output:
t1:Locking Source1
t2:Locking Source2
*///:~
一個簡單死鎖的小小實例。
關於“鎖”還有點懵懂,希望以後能慢慢領悟。