[关闭]
@Yano 2017-08-07T08:36:21.000000Z 字数 1600 阅读 1833

Java 生产者消费者实现

Java


《Java 编程思想》中,使用 厨师-服务员 来表示:生产者、消费者。

思路

chef 在 有 meal 的时候,会释放锁;在制作 meal 时,会获取 waitPerson 的锁,制作完 meal 后,唤醒所有的 waitPerson;

waitPerson 在 没有 meal 的时候,会释放锁;在消费 meal 后,会将 meal 置为 null,操作期间需要获得 chef 的锁。

实现

  1. public class Restaurant {
  2. Meal meal;
  3. ExecutorService exec = Executors.newCachedThreadPool();
  4. WaitPerson waitPerson = new WaitPerson(this);
  5. Chef chef = new Chef(this);
  6. public Restaurant() {
  7. exec.execute(chef);
  8. exec.execute(waitPerson);
  9. }
  10. public static void main(String[] args) {
  11. new Restaurant();
  12. }
  13. }
  1. public class Meal {
  2. private final int orderNum;
  3. public Meal(int orderNum) {
  4. this.orderNum = orderNum;
  5. }
  6. @Override
  7. public String toString() {
  8. return "Meal " + orderNum;
  9. }
  10. }
  1. public class Chef implements Runnable{
  2. private int count = 0;
  3. private Restaurant restaurant;
  4. public Chef(Restaurant restaurant) {
  5. this.restaurant = restaurant;
  6. }
  7. @Override
  8. public void run() {
  9. try {
  10. while (!Thread.interrupted()) { // shutdownNow 后,会退出循环
  11. synchronized (this) {
  12. // 如果有 meal,则释放锁,等待
  13. while (restaurant.meal != null) {
  14. wait();
  15. }
  16. }
  17. if (++ count == 10) {
  18. System.out.println("Out of 10");
  19. restaurant.exec.shutdownNow();
  20. }
  21. synchronized (restaurant.waitPerson) {
  22. restaurant.meal = new Meal(count);
  23. restaurant.waitPerson.notifyAll();
  24. }
  25. TimeUnit.SECONDS.sleep(1);
  26. }
  27. } catch (Exception e) {
  28. System.out.println("Chef interrupted");
  29. }
  30. }
  31. }
  1. public class WaitPerson implements Runnable{
  2. private Restaurant restaurant;
  3. public WaitPerson(Restaurant restaurant) {
  4. this.restaurant = restaurant;
  5. }
  6. @Override
  7. public void run() {
  8. try {
  9. while (!Thread.interrupted()) {
  10. synchronized (this) {
  11. while (restaurant.meal == null) {
  12. wait();
  13. }
  14. }
  15. System.out.println("WaitPerson got " + restaurant.meal);
  16. synchronized (restaurant.chef) {
  17. restaurant.meal = null;
  18. restaurant.chef.notifyAll();
  19. }
  20. }
  21. } catch (Exception e) {
  22. System.out.println("WaitPerson interrupted");
  23. }
  24. }
  25. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注