多线程之生产者与消费者问题

来源:互联网 发布:乐昌网络问政平台 编辑:程序博客网 时间:2024/05/17 01:12

考虑这样一个饭店,他有一个厨师和一个服务生,然后服务生必须等待厨师准备好食物,当厨师准备好食物时,他会通知服务生,然后服务生上菜,

然后返回继续等待。

/** * 食物 */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;    }    @Override    public 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;    }    @Override    public 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.println("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 {    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();    }}
通过判断餐厅中的食物是否为空来控制两个线程是否等待和执行。

效果:

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

原创粉丝点击