主题:wait和notify,notifyall
在下面代码中,当一个进程执行wait语句时有个进程执行notifyAll语句,那么被唤醒的进程是从那一句开始执行呢?
//以下是P原语
public static synchronized void P(int semaphore){
semaphore--;
if(semaphore<0){
try{
Ph.class.wait();
}catch(InterruptedException e){} }
}
//以下是V原语
public static synchronized void V(int semaphore){
semaphore++;
Ph.class.notifyAll();
}
整个类如下:
class Philosopher extends Thread{
static int mutex=2;
static int[] Chopstick={1,1,1,1,1};
private int number;
public Philosopher(int num){
number=num;
start();
}
public String toString(){
return "Philosopher"+number;
}//以下是P原语
public static synchronized void P(int semaphore){
semaphore--;
if(semaphore<0){
try{
Philosopher.class.wait();
}catch(InterruptedException e){} }
}//以下是V原语
public static synchronized void V(int semaphore){
semaphore++;
Philosopher.class.notify();
}
public void think(){
System.out.println(this+" is thinking");
try{
sleep((int)(50*Math.random()));
}
catch(InterruptedException e){
//throw new RuntimeException(e);
}
}
public void eat(){
P(mutex);
P(Chopstick[(number+1)%5]);
//为简写代码,默认取筷子的顺序是相同的,都是先取右边
System.out.println(this+"拿到右边的筷子等待左边的筷子");
try{
Thread.sleep(10);
}catch(InterruptedException e){}
P(Chopstick[(number)%5]);
System.out.println(this+"拿到两边的筷子,正在进餐");
//V(mutex);
V(Chopstick[(number+1)%5]);
V(Chopstick[(number)%5]);
V(mutex);
}
public void run()
{
while(true)
{
think();
eat();
}
}
}
//以下是P原语
public static synchronized void P(int semaphore){
semaphore--;
if(semaphore<0){
try{
Ph.class.wait();
}catch(InterruptedException e){} }
}
//以下是V原语
public static synchronized void V(int semaphore){
semaphore++;
Ph.class.notifyAll();
}
整个类如下:
class Philosopher extends Thread{
static int mutex=2;
static int[] Chopstick={1,1,1,1,1};
private int number;
public Philosopher(int num){
number=num;
start();
}
public String toString(){
return "Philosopher"+number;
}//以下是P原语
public static synchronized void P(int semaphore){
semaphore--;
if(semaphore<0){
try{
Philosopher.class.wait();
}catch(InterruptedException e){} }
}//以下是V原语
public static synchronized void V(int semaphore){
semaphore++;
Philosopher.class.notify();
}
public void think(){
System.out.println(this+" is thinking");
try{
sleep((int)(50*Math.random()));
}
catch(InterruptedException e){
//throw new RuntimeException(e);
}
}
public void eat(){
P(mutex);
P(Chopstick[(number+1)%5]);
//为简写代码,默认取筷子的顺序是相同的,都是先取右边
System.out.println(this+"拿到右边的筷子等待左边的筷子");
try{
Thread.sleep(10);
}catch(InterruptedException e){}
P(Chopstick[(number)%5]);
System.out.println(this+"拿到两边的筷子,正在进餐");
//V(mutex);
V(Chopstick[(number+1)%5]);
V(Chopstick[(number)%5]);
V(mutex);
}
public void run()
{
while(true)
{
think();
eat();
}
}
}