public class Solution implements Runnable {
Semaphore first=new Semaphore(3);
Semaphore second=new Semaphore(2);
boolean[] chopsticks =new boolean[5];
@Override
public void run() {
int id=((int)Thread.currentThread().getId())%5;
try {
getchopsticks(id);
} catch (InterruptedException e) {
e.printStackTrace();
}
release(id);
}
public void getchopsticks(int id) throws InterruptedException {
while(true) {
if(!chopsticks[(id+5)%5]) {
first.acquire();
chopsticks[(id+5)%5]=true;
while(true) {
if(!chopsticks[(id+4)%5]) {
second.acquire();
chopsticks[(id+4)%5]=true;
return;
}
}
}
}
}
public void release(int id) {
second.release();
chopsticks[(id+4)%5]=false;
first.release();
chopsticks[(id+5)%5]=false;
}
}
哲学家就餐问题解决方案(java)
最新推荐文章于 2021-07-06 22:58:42 发布