package eatingQuestionOfPhilosopher;
import java.util.Random;
public class EatQuestionOfPhilosopher {
public static void main(String[] args) {
//哲学家数量
final int philosopherCount = 5;
//new一个信号量
Semaphore semaphore = new Semaphore(philosopherCount);
//创建相应哲学家数量的线程
for(int i=1;i<=philosopherCount;i++) {
new Thread(new Philosopher(i,semaphore,philosopherCount)).start();
}
}
}
class Semaphore {
//筷子信号标识
private int chopsticks[];
//访问筷子数组的锁
private int mutex = 1;
//初始化信号量,给筷子数组定义长度并全部复制为1,表示可用
public Semaphore(int philosopherCount) {
chopsticks = new int[philosopherCount];
for(int i=0;i<philosopherCount;i++) {
chopsticks[i] = 1;
}
}
//给筷子资源访问上锁
private void waitMutex() {
while(true) {
sleep(1);
if(mutex == 1) {
break;
}
}
mutex = 0;
}
//给筷子资源访问开锁
private void signalMutex() {
mutex = 1;
}
//哲学家等待进餐想要拿起筷子的函数
public boolean wait(int left,int right) {
//筷子资源是临界资源,上锁访问
waitMutex();
if( chopsticks[left] == 1 && chopsticks[right]==1 ) {
chopsticks[left]=0;
chopsticks[right]=0;
//筷子资源是临界资源,访问完成开锁
signalMutex();
return true;
} else {
//筷子资源是临界资源,访问完成开锁
signalMutex();
return false;
}
}
//哲学家进餐完毕放下筷子的函数
public void signal (int left,int right) {
waitMutex();
chopsticks[left]=1;
chopsticks[right]=1;
signalMutex();
}
//为了代码整洁,减少大量try,catch块
public void sleep (int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
//哲学家类
class Philosopher implements Runnable {
//哲学家的位置
private int location;
//信号量
private Semaphore semaphore;
//哲学家数量
private int philosopherCount;
//随机数
private Random random = new Random();
//初始化哲学家,定义位置,共用的信号量,哲学家数量
public Philosopher (int location,Semaphore semaphore,int philosopherCount) {
this.location = location;
this.semaphore = semaphore;
this.philosopherCount = philosopherCount;
}
@Override
public void run() {
// TODO 自动生成的方法存根
while(true) {
//随机准备一段时间
semaphore.sleep((random.nextInt(10)+1)*100);
//哲学家想要拿起筷子
while(true) {
semaphore.sleep(1);
if(semaphore.wait(location-1, location%philosopherCount)) {
break;
}
}
//进餐过程,随机进餐一段时间
System.out.println("哲学家"+location+"开始进餐");
semaphore.sleep((random.nextInt(10)+1)*100);
System.out.println("\t哲学家"+location+"进餐结束");
//放下筷子
semaphore.signal(location-1, location%philosopherCount);
//随机休息一段时间
semaphore.sleep((random.nextInt(10)+1)*100);
}
}
}