读书人

编程思维:生产者和消费者

发布时间: 2012-10-27 10:42:26 作者: rapoo

编程思想:生产者和消费者

请考虑这这样一个饭店,它有一个厨师和一个服务员。服务员必须等待厨师,厨师准备好后通知服务员,服务员上菜后继续等待。

?

?

package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;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;}@Overridepublic void run() {try {while(!Thread.interrupted()){synchronized (this) {while(restaurant.meal==null){wait();}}System.out.println("Waitperson got "+restaurant.meal);synchronized(restaurant.chef){restaurant.meal=null;restaurant.chef.notifyAll();}}} catch (InterruptedException e) {System.out.println("Waitperson interrupted");}}}class Chef implements Runnable{private Restaurant restaurant;private int count=0;public Chef(Restaurant r) {restaurant=r;}@Overridepublic void run() {try {while(!Thread.interrupted()){synchronized (this) {//while(restaurant.meal!=null){wait();//}}if(++count==10){System.out.println("out of food, closing");restaurant.exec.shutdownNow();   }System.out.print("Order up!");synchronized(restaurant.waitPerson){restaurant.meal=new Meal(count);restaurant.waitPerson.notifyAll();}TimeUnit.MILLISECONDS.sleep(100);}} catch (InterruptedException e) {System.out.println("Chef interrupted");}}}public class Restaurant {/** * @param args */Meal meal;ExecutorService exec=Executors.newCachedThreadPool();WaitPerson waitPerson=new WaitPerson(this);Chef chef=new Chef(this);public Restaurant(){exec.execute(chef);//启动chef线程exec.execute(waitPerson);//启动waitPerson线程}public static void main(String[] args) {new Restaurant();}}

?结果:

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

WaitPerson interrupted

Order up! Chef interrupted

?

shutdownNow()向所有由ExecutorService 启动的任务发送interrupt()。但在Chef中,任务并没有在获得该interrupt()后立即关闭,因为当任务试图进入一个(可中断的)阻塞操作时,这个中断只能抛出InterruptedException。因此,首先显示了"Order up!",然后当Chef试图sleep时,抛出了InterruptedException。如果移除对sleep的调用,那么任务将回到run循环的顶部,并由Thread.interrupted()测试而退出,同时并不抛出异常。

读书人网 >编程

热点推荐