亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

大神幫我看看自己寫的多線程哪里出了問題

主要功能是兩個線程操作一個變量,一個讓它+1,一個讓它-1然后交替輸出

public?class?Res?{
	private?boolean?flag?=?true;
	private?int?x?=?1;

	public?synchronized?void?print1()?{
		if?(!flag)?{
			try?{
				this.wait();
			}?catch?(InterruptedException?e)?{
				e.printStackTrace();
			}
		}
		System.out.println(x++);
		flag?=?false;
		this.notify();

	}

	public?synchronized?void?print2()?{

		if?(flag)?{
		}
		try?{
			this.wait();
		}?catch?(InterruptedException?e)?{
			e.printStackTrace();
		}

		System.out.println(x--);
		flag?=?true;
		this.notify();
	}

}
public?class?PrintOne?implements?Runnable{
	private?Res?r;
	public?PrintOne(Res?r){
		this.r=r;
	}
public?void?run(){
	while(true){
		r.print1();
	}
}
}
public?class?PrintTwo?implements?Runnable{
	private?Res?r;
	public?PrintTwo(Res?r){
		this.r=r;
	}
public?void?run(){
	while(true){
		r.print2();
	}
}
}
public?class?Test?{
	public?static?void?main(String[]?args)?{
		Res?r=new?Res();
		new?Thread(new?PrintOne(r)).start();
		new?Thread(new?PrintTwo(r)).start();
	}

}

運行結果就是輸出一個1,就停住了,哪里死鎖了還是全部等待了

正在回答

1 回答

你的print2方法里,wait方法沒有在if分支里。

0 回復 有任何疑惑可以回復我~
#1

Juneava 提問者

哦哦,老是犯低級錯誤!感謝指導!看的真仔細!
2016-11-20 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

大神幫我看看自己寫的多線程哪里出了問題

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號