关于Java并发多线程中断机制

月夜归醉 发布于 2015/08/18 09:23
阅读 198
收藏 0

在Java编程思想710-711页有个关于生产者和消费者的多线程协作示例。这个示例有  厨师,服务者,饭店,菜。服务员等待厨师准备好膳食,当厨师准备好时,通知服务员。服务员上菜后,返回继续等待。

为什么调用exec.shutdownNow()不能立刻停止线程

Java编程思想是这样解释的:shutdownNow()将向所有有ExecutorService启动的任务发送interrupt(),但是在Chef中,任务并没有在获取该interrupt()之后立即关闭,因为当任务试图进入一个(可中断的)阻塞操作时,这个中断只能抛出InterruptedException。因此,你将看到首先显示了“Order up!",然后当Chef试图调用sleep()时,抛出了InterruptedException.  

表示上面这段话不明白,求大神解析一下

package 并发;
import java.util.concurrent.*;
import static mytools.Print.*;

class Meal{
 private final int orderNum;
 public Meal(int orderNum){
  this.orderNum=orderNum;
 }
 public String toString(){
  return "Meal "+orderNum;
 }
}

class WaitPerson implements Runnable{
 private Restaurant restaurant;
 public WaitPerson(Restaurant r){
  restaurant=r;
 }
 public void run(){
  try{
   while(!Thread.interrupted()){
    synchronized(this){
     while(restaurant.meal==null)
      wait();//...for the chef to produce a meal
    }
    print("Waitperson got "+restaurant.meal);
    synchronized(restaurant.chef){
     restaurant.meal=null;
     restaurant.chef.notifyAll();
    }
   }
  }catch(InterruptedException e){
   print("Waitperson interrupted");
  }
 }
}

class Chef implements Runnable{
 private Restaurant restaurant;
 private int count=0;
 public Chef(Restaurant r){
  restaurant=r;
 }
 public void run(){
  try{
   while(!Thread.interrupted()){
    synchronized(this) {
     while(restaurant.meal!=null)
      wait();
    }
    if(++count==10){
     print("Out of food,closing");
     restaurant.exec.shutdownNow();
   
    }
    printnb("Order up! ");
    synchronized(restaurant.waitPerson){
     restaurant.meal=new Meal(count);
     restaurant.waitPerson.notifyAll();
    }
    TimeUnit.MILLISECONDS.sleep(100);
  
   
   }
  }catch(InterruptedException e){
   print("Chef interrupted");
  }
 }
}
public class Restaurant {
 Meal meal;
 ExecutorService exec=Executors.newCachedThreadPool();
 WaitPerson waitPerson=new WaitPerson(this);
 Chef chef=new Chef(this);
 public Restaurant(){
  exec.execute(chef);
  exec.execute(waitPerson);
 }
 public static void main(String[] args){
  new Restaurant();
 }
}

/*Output

Order up! Waitperson got Meal 1
Order up! Waitperson got Meal 2
Order up! Waitperson got Meal 3
Order up! Waitperson got Meal 4
Order up! Waitperson got Meal 5
Order up! Waitperson got Meal 6
Order up! Waitperson got Meal 7
Order up! Waitperson got Meal 8
Order up! Waitperson got Meal 9
Out of food,closing
Order up! Waitperson interrupted
Chef interrupted

*/


加载中
返回顶部
顶部