`

线程 死锁

 
阅读更多

 

 

 

/**
 * 过多的同步方法可能造成死锁
 * @author Administrator
 *
 */
public class SynDemo03 {

	/**
	 * @param args
	 */
	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); // 持有同样的对象 g m
		Thread proxy2 = new Thread(t2);// 持有同样的对象 g m
		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;
	}

	@Override
	public void run() {
		while(true){
			test();
		}
	}
	
	public void test(){
		synchronized(goods){ // 先给货  
			try {
				Thread.sleep(100);//增加时间延迟 构建锁死条件
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized(money){ // 在给钱
				
			}
			
		}
		System.out.println("一手给钱");
	}
	
	
	
	
	
	
	
}

class Test2  implements Runnable{
	Object goods ;
	Object money ;
	public Test2(Object goods, Object money) {
		super();
		this.goods = goods;
		this.money = money;
	}

	@Override
	public void run() {
		while(true){
			test();
		}
	}
	
	public void test(){
		synchronized(money){ // 先给钱
			try {
				Thread.sleep(100); // 增加时间延迟 构建死锁现象
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized(goods){// 在给货 
				
			}
			
		}
		System.out.println("一手给货");
	}
	
	
	
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics