資源簡(jiǎn)介
利用JAVA解決哲學(xué)家進(jìn)餐的經(jīng)典問題。
很簡(jiǎn)單的小程序。
代碼片段和文件信息
class?ChopStick?{????//筷子類
boolean?available;
????ChopStick()?{
????????available=true;??//可以拿起
???}
????public?synchronized?void?takeup()?{??//拿起動(dòng)作
????????while(!available)?{
????????????try?{
????????????????wait();?
????????????????System.out.println(“哲學(xué)家等待另一根筷子“);??
????????????}?catch(InterruptedException?e)?{?}
?????}
????????available=false;
????}
????
????public?synchronized?void?putdown()?{??//放下動(dòng)作
????????available=true;
????????notify();
????}
}
class?Philosopher?extends?Thread?{???//哲學(xué)家類
????ChopStick?left?right;??
????int?philo_num;??//哲學(xué)家編號(hào)
?????
?????Philosopher?(int?num?ChopStick?c1?ChopStick?c2)?{
?????????philo_num?=?num;
?????????left?=?c1;
?????????right?=?c2;
?????????setDaemon(true);??//此函數(shù)設(shè)true時(shí),關(guān)閉主線程,子線程也跟著關(guān)閉
?????????//否則,關(guān)閉主線程
評(píng)論
共有 條評(píng)論