考虑有这样一个饭店 他有一个厨师和一个服务员 这个服务员必须等待厨师准备好食物。当厨师准备好时会通知服务员 之后服务员上菜,这样一个线程协作 厨师作为生产者 而 服务员作代表消费者
菜的java实例
package test.thread.ProducerAndConsumer; public class Meal { private final int orderNum; public Meal(int orderNum) { this.orderNum = orderNum; } @Override public String toString() { return "Meal [orderNum=" + orderNum + "]"; } }
服务员的实例
package test.thread.ProducerAndConsumer; public class WaitPerson implements Runnable { private Restaurant restautant; public WaitPerson(Restaurant r) { this.restautant = r; } @Override public void run() { try{ while(!Thread.currentThread().isInterrupted()){ /** * 同步服务员取餐 */ synchronized (this) { while(restautant.meal==null){ //菜还没有做好 服务员请等待 wait(); } } System.out.println("服务员得到了"+restautant.meal); synchronized (restautant.chef) { //菜没有了 restautant.meal = null; //唤醒厨师 请厨师做菜 restautant.chef.notify(); } } }catch(InterruptedException e){ System.out.println("服务员run中断"); } } }
厨师的实例
package test.thread.ProducerAndConsumer; import java.util.concurrent.TimeUnit; import javax.management.timer.Timer; public class Chef implements Runnable { private Restaurant restaurant; private int count = 0; public Chef(Restaurant restaurant) { this.restaurant = restaurant; } @Override public void run() { try{ while(!Thread.currentThread().isInterrupted()){ synchronized (this) { while(restaurant.meal!=null){ //菜已经做好了 厨师请耐心等待 厨师任务线程被挂起 wait(); } } /** * 饭店储备只够10个菜 */ 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.notify(); } /*TimeUnit.MILLISECONDS.sleep(100);*/ } }catch(InterruptedException e){ System.out.println("Chef 中断"); } } }
饭店的实例
package test.thread.ProducerAndConsumer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Restaurant { WaitPerson waitPerson = new WaitPerson(this); Meal meal; ExecutorService exec = Executors.newCachedThreadPool(); Chef chef = new Chef(this); public Restaurant() { exec.execute(chef); exec.execute(waitPerson);} public static void main(String[] args) { new Restaurant(); } }