public class Meal { private final int orderNum; public Meal(int orderNum) { this.orderNum = orderNum; } public String toString() { return "Meal" + orderNum; } }
/** * 生产者 */ public class Producer implements Runnable { private Restaurant restaurant; private int count = 0; public Producer(Restaurant restaurant) { this.restaurant = restaurant; } @Override public void run() { try { while (!Thread.interrupted()) { synchronized (this) { while (restaurant.meal != null) { wait();// 等消费 } } if (++count == 10) { System.out.println("买完了"); restaurant.exec.shutdownNow(); } System.out.println("订单来了!"); synchronized (restaurant.customer) { restaurant.meal = new Meal(count); System.out.println("做完了"); restaurant.customer.notifyAll(); } TimeUnit.MILLISECONDS.sleep(100); } } catch (InterruptedException e) { System.out.println("消费者休息了!"); } } }
/** * 消费者 */ public class Customer implements Runnable { private Restaurant restaurant; public Customer(Restaurant restaurant) { this.restaurant = restaurant; } @Override public void run() { try { while (!Thread.interrupted()) { synchronized (this) { while (restaurant.meal == null) { wait();// 等生产者生产 } } System.out.println("producer got " + restaurant.meal); synchronized (restaurant.customer) { restaurant.meal = null; restaurant.customer.notifyAll(); } } } catch (InterruptedException e) { System.out.println("生产者休息了!"); } } }
public class Restaurant { Meal meal; ExecutorService exec = Executors.newCachedThreadPool(); Producer producer = new Producer(this); Customer customer = new Customer(this); public Restaurant() { exec.execute(producer); exec.execute(customer); } }
public class Main { public static void main(String[] args) { new Restaurant(); } }