Java是一門(mén)強(qiáng)類(lèi)型、面向?qū)ο蟆⒖缙脚_(tái)的編程語(yǔ)言,被廣泛運(yùn)用于各種類(lèi)型的應(yīng)用開(kāi)發(fā)中。然而,在Java編程時(shí),我們常常會(huì)遇到死鎖和活鎖等問(wèn)題,這些問(wèn)題可能導(dǎo)致應(yīng)用程序的運(yùn)行出現(xiàn)異常。
死鎖
public class DeadLockDemo { private static final Object RESOURCE_A = new Object(); private static final Object RESOURCE_B = new Object(); public static void main(String[] args) { Thread thread1 = new Thread(() -> { synchronized (RESOURCE_A) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (RESOURCE_B) { System.out.println("Thread-1 acquired lock on RESOURCE_B"); } } }); Thread thread2 = new Thread(() -> { synchronized (RESOURCE_B) { synchronized (RESOURCE_A) { System.out.println("Thread-2 acquired lock on RESOURCE_A"); } } }); thread1.start(); thread2.start(); } }
上面的代碼中,我們定義了兩個(gè)資源RESOURCE_A
和RESOURCE_B
,然后定義了兩個(gè)線程thread1
和thread2
。在thread1
里先獲得RESOURCE_A
的鎖,等待1秒后再去獲得RESOURCE_B
的鎖。
而在thread2
里先獲得RESOURCE_B
的鎖,再去獲得RESOURCE_A
的鎖。由于兩個(gè)線程持有了對(duì)方所需的鎖,因此它們會(huì)發(fā)生死鎖,程序無(wú)法正常運(yùn)行。
活鎖
public class LiveLockDemo { private static final AtomicInteger COUNTER = new AtomicInteger(0); public static void main(String[] args) { Thread thread1 = new Thread(() -> { while (COUNTER.get() < 10) { System.out.println("Thread-1 is waiting.."); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (COUNTER.get() % 2 == 0) { COUNTER.getAndIncrement(); } } }); Thread thread2 = new Thread(() -> { while (COUNTER.get() < 10) { System.out.println("Thread-2 is waiting.."); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (COUNTER.get() % 2 != 0) { COUNTER.getAndIncrement(); } } }); thread1.start(); thread2.start(); } }
上面的代碼中,我們定義了一個(gè)計(jì)數(shù)器COUNTER
,然后定義了兩個(gè)線程thread1
和thread2
。thread1
會(huì)增加計(jì)數(shù)器的值,但只會(huì)在計(jì)數(shù)器的值為偶數(shù)時(shí)才增加。而thread2
也會(huì)增加計(jì)數(shù)器的值,但只會(huì)在計(jì)數(shù)器的值為奇數(shù)時(shí)才增加。由于兩個(gè)線程都需要同時(shí)滿足自己的條件才能增加計(jì)數(shù)器的值,因此它們可能會(huì)一直在滿足對(duì)方的條件而無(wú)法增加計(jì)數(shù)器的值,這就是活鎖。