`
斌强-朱
  • 浏览: 48677 次
社区版块
存档分类
最新评论

线程死锁

 
阅读更多


class Zhangsan {
	public void say(){
		System.out.println("张三对李四说:你把画给我,我把书给你");
	}

	public void get(){
		System.out.println("张三得到了画");
	}
}

class Lisi {
	public void say(){
		System.out.println("李四对张三说:你把书给我,我把画给你");
	}

	public void get(){
		System.out.println("李四得到了书");
	}
}

public class T2 implements Runnable{
	private static Zhangsan zs = new Zhangsan();
	private static Lisi ls = new Lisi();
	private boolean flag = false;

	@Override
	public void run(){
		if(flag){
			synchronized(zs){
				zs.say();
				try{
					Thread.sleep(500);
				}catch(Exception e){
					e.printStackTrace();
				}
				synchronized(ls){
					zs.get();
				}

			}
		}else{
			synchronized(ls){
				ls.say();
				try{
					Thread.sleep(500);
				}catch(Exception e){
					e.printStackTrace();
				}
				synchronized(zs){
					ls.get();
				}
			}
		}
	}

	public static void main(String[] args){
		T2 t1 = new T2();
		T2 t2 = new T2();
		t1.flag = true;
		t2.flag = false;

		Thread th1 = new Thread(t1);
		Thread th2 = new Thread(t2);

		th1.start();
		th2.start();
	}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics