哲学家类:
public class Philosopher extends Thread {
int number;
Chopsticks chop;
private String name;
//定义无参构造
public Philosopher(){
}
//定义带参构造
public Philosopher(int number,Chopsticks chop){
this.number = number;
this.chop = chop;
}
//重写run方法
public void run(){
while(true){
chop.takeup();
eating();
chop.putdown();
thinking();
}
}
//哲学家进餐方法
public void eating(){
System.out.println("哲学家"+Thread.currentThread().getName()+"正在进餐");
try{
Thread.sleep((int)(Math.random()*10000));
}catch(InterruptedException e){
}
}
//哲学家思考方法
public void thinking(){
System.out.println("哲学家"+Thread.currentThread().getName()+"进餐毕,正在思考");
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
}
}
public static void main(String[] args) {
Chopsticks chop = new Chopsticks();
for(int j=0;j<5;j++)
new Philosopher(j,chop).start();
}
}
筷子类:
public class Chopsticks {
private int s[]={0,0,0,0,0};
public synchronized void takeup(){
int i = Integer.parseInt(Thread.currentThread().getName().substring(7));
int j = i-1;
if(i==0){
j = i;
i = 4;
}
while(s[i]==1){
try{
wait();
}catch(InterruptedException e){
}
}
s[i]=1;
while(s[j]==1){
try{
wait();
}catch(InterruptedException e){
}
}
s[j]=1;
}
public synchronized void putdown(){
int i = Integer.parseInt(Thread.currentThread().getName().substring(7));
s[i]=0;
s[(i+1)%5]=0;
notifyAll();
}
}