notify和notifyAll
代码如下:
public class Philosopher {
public static void main(String [] args){
ChopStick chopstick_1=new ChopStick("1号筷子");
ChopStick chopstick_2=new ChopStick("2号筷子");
ChopStick chopstick_3=new ChopStick("3号筷子");
ChopStick chopstick_4=new ChopStick("4号筷子");
Philosopher_Using pu_1=new Philosopher_Using("哲学家_1",chopstick_1,chopstick_2);
Philosopher_Using pu_2=new Philosopher_Using("哲学家_2",chopstick_2,chopstick_3);
Philosopher_Using pu_3=new Philosopher_Using("哲学家_3",chopstick_3,chopstick_4);
Philosopher_Using pu_4=new Philosopher_Using("哲学家_4",chopstick_4,chopstick_1);
Thread tpu_1=new Thread(pu_1);
Thread tpu_2=new Thread(pu_2);
Thread tpu_3=new Thread(pu_3);
Thread tpu_4=new Thread(pu_4);
tpu_1.start();
tpu_2.start();
tpu_3.start();
tpu_4.start();
}
}
class ChopStick{
protected String chopName;
private boolean available=true;
public ChopStick(String name){
chopName=name;
}
public void getChopStick(){
synchronized(this){
try{
while(available!=true){
this.wait();
}
available=false;
}catch(Exception e){
System.out.println("ERROR!");
}
}
}
public void releaseChopStick(){
synchronized(this){
available=true;
notify();
}
}
public void thinking(String name){
System.out.println(name+"is thinking");
}
public void eatMeal(String name){
System.out.println(name+"is eating");
}
}
class Philosopher_Using implements Runnable{
private String p_name;
ChopStick stickLeft;
ChopStick stickRight;
public Philosopher_Using(String name,ChopStick stickLeft,ChopStick stickRight){
p_name=name;
this.stickLeft=stickLeft;
this.stickRight=stickRight;
}
public void run(){
stickLeft.thinking(p_name);
try{
Thread.currentThread();
Thread.sleep(500);
}catch(Exception e){};
stickLeft.getChopStick();
System.out.println(p_name+"抓起了"+stickLeft.chopName);
stickRight.getChopStick();
System.out.println(p_name+"抓起了"+stickRight.chopName);
stickRight.eatMeal(p_name);
try{
Thread.currentThread();
Thread.sleep(500);
}catch(Exception e){};
stickLeft.releaseChopStick();
System.out.println(p_name+"放下了"+stickLeft.chopName);
stickRight.releaseChopStick();
System.out.println(p_name+"放下了"+stickRight.chopName);
}
}
输出结果:
哲学家_1is thinking
哲学家_4is thinking
哲学家_3is thinking
哲学家_2is thinking
哲学家_1抓起了1号筷子
哲学家_1抓起了2号筷子
哲学家_1is eating
哲学家_3抓起了3号筷子
哲学家_4抓起了4号筷子
哲学家_1放下了1号筷子
哲学家_4抓起了1号筷子
哲学家_4is eating
哲学家_2抓起了2号筷子
哲学家_1放下了2号筷子
哲学家_4放下了4号筷子
哲学家_3抓起了4号筷子
哲学家_3is eating
哲学家_4放下了1号筷子
哲学家_3放下了3号筷子
哲学家_2抓起了3号筷子
哲学家_3放下了4号筷子
哲学家_2is eating
哲学家_2放下了2号筷子
哲学家_2放下了3号筷子
用notify的时候总会有这样的异常现象。还没放下筷子,就会先抓起。是什么原因呢?
改notifyAll的话倒是正常的。不知道两者区别在哪里?