import java.util.concurrent.Semaphore;
public class House
{
int count = 0;
final Semaphore[] chopsticks = new Semaphore[5];
final Semaphore max_num = new Semaphore(4);
House(){
for(int i=0;i<5;i++){
chopsticks[i]=new Semaphore(1);
}
}
static class philosopher_i extends Thread{
public void run(){
while(true){
max_num.acquire();
chopsticks[i].acquire();//拿起左手边的筷子
chopsticks[(i+1)%5].acquire();//拿起右手边的筷子。
eating;
chopsticks[i].release();//放下左手上的筷子。
chopsticks[(i+1)%5].release();//放下右手上的筷子
max_num.release();
}
}
}//i的取值是1到5
public static void main(String [] args){
new philosopher_i().start();//i的取值是1到5
}
}
使用Java中的Semaphore类解决哲学家就餐问题
猜你喜欢
转载自blog.csdn.net/justisme/article/details/86506385
今日推荐
周排行