大廠面試官讓我設計一個死鎖,我的方案是這樣的

題目

面試官:給你15分鐘,設計一個死鎖,應該問題不大吧
我:。。。。

代碼

public class Test implements Runnable{
	
	private static Object obj1 = new Object();
	
	private static Object obj2 = new Object();
	
	private int flag;
	
	public Test(int flag) {
		this.flag = flag;
	}
	
	@Override
	public void run() {
		if(flag == 0) {
			synchronized (obj1) {
				System.out.println(Thread.currentThread().getName() + "得到了obj1的鎖");
				try {
					//確保另一個線程能夠獲得obj2的鎖
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (obj2) {
					System.out.println(Thread.currentThread().getName() + "得到了obj2的鎖");
				}
			}
		}else {
			synchronized (obj2) {
				System.out.println(Thread.currentThread().getName() + "得到了obj2的鎖");
				try {
					//確保另一個線程能夠獲得obj1的鎖
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (obj1) {
					System.out.println(Thread.currentThread().getName() + "得到了obj1的鎖");
				}
			}
		}
		System.out.println(Thread.currentThread().getName() + "運行結束");
	}

	public static void main(String[] args){
		new Thread(new Test(0), "線程一").start();
		new Thread(new Test(1), "線程二").start();
	}
	
}

案例分析

線程1獲得了 obj1 的鎖,卻在等待 obj2 的鎖;線程2獲得了 obj2 的鎖,卻在等待 obj1 的鎖,兩個線程只有先獲取對方的鎖才能夠釋放對方所需要的鎖,進入了無限等待的情況,產生了死鎖。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章