1. package com.pln.gaoji;
    2. //测试生产者消费者问题2:信号灯法,标志位解决
    3. public class TestPC2 {
    4. public static void main(String[] args) {
    5. TV tv = new TV();
    6. new Player(tv).start();
    7. new Watcher(tv).start();
    8. }
    9. }
    10. //生产者--》演员
    11. class Player extends Thread{
    12. TV tv;
    13. public Player(TV tv){
    14. this.tv = tv;
    15. }
    16. @Override
    17. public void run() {
    18. for (int i = 0; i < 20; i++) {
    19. if(i%2==0){
    20. try {
    21. this.tv.play("快了大本营");
    22. } catch (InterruptedException e) {
    23. e.printStackTrace();
    24. }
    25. }else{
    26. try {
    27. this.tv.play("抖音美好生活");
    28. } catch (InterruptedException e) {
    29. e.printStackTrace();
    30. }
    31. }
    32. }
    33. }
    34. }
    35. //消费者--》观众
    36. class Watcher extends Thread{
    37. TV tv;
    38. public Watcher(TV tv){
    39. this.tv = tv;
    40. }
    41. @Override
    42. public void run() {
    43. for (int i = 0; i < 20; i++) {
    44. try {
    45. this.tv.watch();
    46. } catch (InterruptedException e) {
    47. e.printStackTrace();
    48. }
    49. }
    50. }
    51. }
    52. //产品--》节目
    53. class TV{
    54. //演员表演,观众等待 T
    55. //观众观看,演员等待 F
    56. String voice;
    57. boolean flag = true;
    58. //表演
    59. public synchronized void play(String voice) throws InterruptedException {
    60. if(!flag){
    61. this.wait();//表演等待一会
    62. }
    63. System.out.println("演员表演了"+voice);
    64. //通知观众看表演
    65. this.notifyAll();
    66. this.voice = voice;
    67. this.flag = !this.flag;
    68. }
    69. //观众观看
    70. public synchronized void watch() throws InterruptedException {
    71. if(flag){
    72. this.wait();
    73. }
    74. //通知演员表演
    75. System.out.println("观众观看了"+voice);
    76. //通知演员表演
    77. this.notifyAll();
    78. this.flag = !this.flag;
    79. }
    80. }

    image.png