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

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

多線程喚醒問題

public?class?FlagWork?{
	public?static?void?main(String[]?args)?{
		final?Business1?b1?=?new?Business1();
		new?Thread(new?Runnable()?{

			@Override
			public?void?run()?{
				b1.a();
			}
		}).start();
		new?Thread(new?Runnable()?{

			@Override
			public?void?run()?{
				b1.b();
			}
		}).start();
		new?Thread(new?Runnable()?{
			
			@Override
			public?void?run()?{
				b1.c();
			}
		}).start();
	}
}

class?Business1?{
	private?int?flag?=?1;

	public?void?a()?{
		for?(int?i?=?0;?i?<?50;?i++)?{
			synchronized?(this)?{
				while?(flag?!=?1)?{
					try?{
						this.wait();
					}?catch?(InterruptedException?e)?{
						//?TODO?Auto-generated?catch?block
						e.printStackTrace();
					}
				}
				for?(int?j?=?1;?j?<=?10;?j++)?{
					System.out.println("線程a運行"?+?j?+?"次");
				}
				flag?=?2;
				this.notify();
			}
		}
	}

	public?void?b()?{
		for?(int?i?=?0;?i?<?50;?i++)?{
			synchronized?(this)?{
				while?(flag?!=?2)?{
					try?{
						this.wait();
					}?catch?(InterruptedException?e)?{
						//?TODO?Auto-generated?catch?block
						e.printStackTrace();
					}
				}
				for?(int?j?=?1;?j?<=?20;?j++)?{
					System.out.println("線程b運行"?+?j?+?"次");
				}
				flag?=?3;
				this.notify();
			}
		}
	}
	public?void?c()?{
		for?(int?i?=?0;?i?<?50;?i++)?{
			synchronized(this){
				while(flag!=3){
					try?{
						this.wait();
					}?catch?(InterruptedException?e)?{
						//?TODO?Auto-generated?catch?block
						e.printStackTrace();
					}
				}
				for?(int?j?=?1;?j?<=?30;?j++)?{
					System.out.println("線程c運行"+j+"次");
				}
				flag?=?1;
				this.notifyAll();
			}
		}
	}
}

A線程先運行10次,然后B線程運行20次,然后C線程運行30次,如此反復50次的代碼,為什么次c方法里要用this.notifyAll,而用this.notify就不行


正在回答

舉報

0/150
提交
取消

多線程喚醒問題

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

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

幫助反饋 APP下載

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

公眾號

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