1.4 編寫(xiě)一個(gè)死鎖
讓我們以??有趣的方式來(lái)探討死鎖吧!這個(gè)問(wèn)題真的很經(jīng)典,死鎖的四個(gè)條件我們都可以背得滾瓜爛熟。但現(xiàn)在,讓我們不僅背它們,還要寫(xiě)一個(gè)死鎖出來(lái),看看它是如何在代碼中發(fā)生的。思路是這樣的:我們定義了兩個(gè)ArrayList,然后讓它們同時(shí)拿著鎖A和鎖B。接著,有兩個(gè)線程,一個(gè)是線程1,一個(gè)是線程2。線程1先拿住了鎖A,然后請(qǐng)求鎖B,而線程2拿住了鎖B,請(qǐng)求鎖A。這就像兩個(gè)人相互卡住不讓對(duì)方通過(guò),結(jié)果就是誰(shuí)也不愿意放棄已經(jīng)拿到的鎖。
```java
public class DeadLock {
??public static void main(String[] args) {
????final List list1 = Arrays.asList(1, 2, 3);
????final List list2 = Arrays.asList(4, 5, 6);
????new Thread(new Runnable() {
??????@Override
??????public void run() {
????????synchronized (list1) {
??????????for (Integer i : list1) {
????????????System.out.println(i);
??????????}
??????????try {
????????????Thread.sleep(1000);
??????????} catch (InterruptedException e) {
????????????e.printStackTrace();
??????????}
??????????synchronized (list2) {
????????????for (Integer i : list2) {
??????????????System.out.println(i);
????????????}
??????????}
????????}
??????}
????}).start();
????new Thread(new Runnable() {
??????@Override
??????public void run() {
????????synchronized (list2) {
??????????for (Integer i : list2) {
????????????System.out.println(i);
??????????}
??????????try {
????????????Thread.sleep(1000);
??????????} catch (InterruptedException e) {
????????????e.printStackTrace();
??????????}
??????????synchronized (list1) {
????????????for (Integer i : list1) {
??????????????System.out.println(i);
????????????}
??????????}
????????}
??????}
????}).start();
??}
}
```
這段代碼就像兩個(gè)人互相拿著兩把鎖,然后又試圖拿對(duì)方的鎖,結(jié)果卡住了。運(yùn)行這段代碼,你會(huì)看到死鎖發(fā)生了,兩個(gè)線程都無(wú)法繼續(xù)執(zhí)行下去,就像兩個(gè)??握手的人都不松開(kāi)一樣,這就是死鎖的奇妙之處!希望這個(gè)例子能幫助你更好地理解死鎖的概念和發(fā)生原因。????
標(biāo)簽: