Cooker.java 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package J20250731.demo01_cooker_foodie;
  2. /**
  3. * @author WanJl
  4. * @version 1.0
  5. * @title Cooker
  6. * @description
  7. * @create 2025/7/31
  8. */
  9. public class Cooker implements Runnable{
  10. /**
  11. * 1.判断是否有包子,决定当前线程是否执行
  12. * 2.如果有包子,就进入等待状态,如果没有包子,继续执行,生产包子
  13. * 3.生产包子之后,更新桌子上包子状态,唤醒消费者消费包子
  14. */
  15. @Override
  16. public void run() {
  17. while (true){
  18. synchronized (Desk.lock){
  19. if (Desk.count==0){
  20. break;
  21. }else {
  22. if (Desk.flag){
  23. //生产者等待
  24. try {
  25. Desk.lock.wait();
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. }else {
  30. //生产者生产
  31. System.out.println("厨师"+Thread.currentThread().getName()+"正在生产包子");
  32. Desk.count++;
  33. Desk.flag=true;
  34. System.out.println("生产后包子增加到:"+Desk.count);
  35. Desk.lock.notifyAll();
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }