1. 程式人生 > >java面試題---請用多執行緒寫死鎖

java面試題---請用多執行緒寫死鎖

java面試題---用多執行緒寫死鎖

(請參考本部落格對同步鎖的文章進行理解)
public class dead {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadOne one=new ThreadOne();
		ThreadTwo two=new ThreadTwo();
		sharing obj1=new sharing();
		sharing obj2=new sharing();
		one.obj1=obj1;
		one.obj2=obj2;
		two.obj1=obj1;
		two.obj2=obj2;
		one.obj1=two.obj2;
		one.obj2=two.obj1;
	
		one.start();
		two.start();
	}

}
class sharing{
	
}
class ThreadOne extends Thread{
	sharing obj1;
	sharing obj2;
	public void run(){
		synchronized (obj1) {
			System.out.println("我進入了ThreadOne外部鎖");
			synchronized (obj2) {
				System.out.println("我進入了ThreadOne內部鎖");
			}
		}
	}
}
class ThreadTwo extends Thread{
	sharing obj1;
	sharing obj2;
	public void run(){
		synchronized (obj1) {
			System.out.println("我進入了ThreadTwo外部鎖");
			synchronized (obj2) {
				System.out.println("我進入了ThreadTwo內部鎖");
			}
		}
	}
}
列印輸出: 我進入了ThreadOne外部鎖
我進入了ThreadTwo外部鎖
(兩個執行緒都在等在同步資源釋放自己的鎖,一直處於等待狀態)