package test;
import java.lang.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.event.TreeWillExpandListener;
class philosopher extends Thread{
public chopsticks left,right;
public int number;
public int cnt=1;
public philosopher(int x,chopsticks c2,chopsticks c1) {
number=x;
left= c2;right= c1;
}
public void eat(){
left.takeup();
right.takeup();
System.out.println(number+"号哲学家在第"+this.cnt+"次吃饭");
try {
this.sleep((long) (Math.random()*1500+1500));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(number+"号哲学家吃好了");
this.cnt++;
left.pudown();
right.pudown();
}
public void thinking(){
System.out.println(this.number+"号哲学家在思考");
try {
this.sleep((long) (1500+Math.random()*1500));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run(){
super.run();
while(this.cnt<=3){
int x=(int) (Math.random()*3);
if(x==1)
thinking();
else
eat();
}
}
}
class chopsticks extends Thread{
public boolean available=true;
public int number;
public synchronized void takeup() {
while(this.available==false){
try {
wait();
System.out.println("请求"+this.number+"号筷子,但是它正在被另一个哲学家使用");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.available=false;
}
public synchronized void pudown(){
this.available=true;
notifyAll();
}
public chopsticks(int x) {
number=x;
}
}
public class test2 {
public static void main(String[] args){
System.out.println("philosopher 吃三次饭");
System.out.println("philosopher's dining start");
chopsticks c1= new chopsticks(1);
chopsticks c2= new chopsticks(2);
chopsticks c3= new chopsticks(3);
chopsticks c4= new chopsticks(4);
chopsticks c5= new chopsticks(5);
philosopher p1=new philosopher(1,c5,c1) ;
philosopher p2=new philosopher(2,c1,c2) ;
philosopher p3=new philosopher(3,c2,c3) ;
philosopher p4=new philosopher(4,c3,c4) ;
philosopher p5=new philosopher(5,c4,c5) ;
p2.start();
p4.start();
p1.start();
p3.start();
p5.start();
System.out.println("主线程到了尾部");
}
}