Java中的死鎖和非死鎖結(jié)果是兩種不同的情況。死鎖指兩個或多個進(jìn)程之間互相持有其他進(jìn)程正在請求的資源的情況,導(dǎo)致這些進(jìn)程都無法繼續(xù)執(zhí)行,陷入了死循環(huán)。非死鎖則是指沒有任何進(jìn)程持有其他進(jìn)程正在請求的資源。
一個典型的死鎖的例子是兩個線程互相持有對方需要的鎖,導(dǎo)致雙方都無法繼續(xù)執(zhí)行下去。例如:
public class DeadlockExample { public static void main(String[] args) { Object lock1 = new Object(); Object lock2 = new Object(); Thread thread1 = new Thread(new Runnable() { @Override public void run() { synchronized (lock1) { System.out.println("Thread 1 acquired lock 1"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock2) { System.out.println("Thread 1 acquired lock 2"); } } } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { synchronized (lock2) { System.out.println("Thread 2 acquired lock 2"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock1) { System.out.println("Thread 2 acquired lock 1"); } } } }); thread1.start(); thread2.start(); } }
代碼中創(chuàng)建了兩個對象鎖lock1和lock2,然后啟動了兩個線程。兩個線程都先獲取一個鎖,等待一段時間后再嘗試獲取另一個鎖。由于線程1持有l(wèi)ock1,而線程2持有l(wèi)ock2,它們都在等待對方釋放鎖而無法繼續(xù)執(zhí)行,形成了死鎖狀態(tài)。
相比之下,非死鎖的情況則是所有線程都沒有互相持有對方需要的資源。例如下面的代碼:
public class NonDeadlockExample { public static void main(String[] args) { Object lock1 = new Object(); Object lock2 = new Object(); Thread thread1 = new Thread(new Runnable() { @Override public void run() { synchronized (lock1) { System.out.println("Thread 1 acquired lock 1"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { synchronized (lock2) { System.out.println("Thread 2 acquired lock 2"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); thread1.start(); thread2.start(); } }
這個代碼中,兩個線程分別持有兩個不同的鎖,它們互相之間不需要對方持有的鎖,因此不會出現(xiàn)死鎖。