[線程]——死鎖

//過多的同步方法可能造成死鎖
public class SynDemo03 {
	public static void main(String[] args) {
		Object g=new Object();
		Object m=new Object();
		Test t1=new Test(g, m);
		Test2 t2=new Test2(g, m);
		Thread proxy=new Thread(t1);//Runnable proxy=new Thread(t1);多態不能調用新增方法
		Thread proxy2=new Thread(t2);
		proxy.start();
		proxy2.start();
	}
}
class Test implements Runnable{
	Object goods;
	Object money;
	//////////////////////////////////////////////////////
	public Test(Object goods, Object money) {
		super();
		this.goods = goods;
		this.money = money;
	}
	public Object getGoods() {
		return goods;
	}
	public void setGoods(Object goods) {
		this.goods = goods;
	}
	public Object getMoney() {
		return money;
	}
	public void setMoney(Object money) {
		this.money = money;
	}
	////////////////////////////////////////////////
	@Override
	public void run() {
		while(true){
			test();
		}
	}
	public void test(){
		synchronized (money) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			synchronized (goods) {
			}
		}
		System.out.println("一手給貨。。。。");
	}
}
class Test2 implements Runnable{
	Object goods;
	Object money;
	///////////////////////////////////////////////////////
	public Test2(Object goods, Object money) {
		super();
		this.goods = goods;
		this.money = money;
	}
	public Object getGoods() {
		return goods;
	}
	public void setGoods(Object goods) {
		this.goods = goods;
	}
	public Object getMoney() {
		return money;
	}
	public void setMoney(Object money) {
		this.money = money;
	}
	////////////////////////////////////////////
	@Override
	public void run() {
		while(true){
			test();
		}
	}
	public void test(){
		synchronized (goods) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			synchronized (money) {
				
			}
		}
		System.out.println("一手給錢。。。。");
	}
}

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