1. package com.pln.gaoji;
    2. public class TestPC {
    3. public static void main(String[] args) {
    4. SynContainer container = new SynContainer();
    5. new Producer(container).start();
    6. new Customer(container).start();
    7. }
    8. }
    9. //生产者
    10. class Producer extends Thread{
    11. SynContainer container;
    12. public Producer(SynContainer container){
    13. this.container = container;
    14. }
    15. @Override
    16. public void run() {
    17. for (int i = 0; i < 100; i++) {
    18. try {
    19. container.push(new Chicken(i));
    20. } catch (InterruptedException e) {
    21. e.printStackTrace();
    22. }
    23. System.out.println("生产了"+i+"只鸡");
    24. }
    25. }
    26. }
    27. //消费者
    28. class Customer extends Thread{
    29. SynContainer container;
    30. public Customer(SynContainer container){
    31. this.container = container;
    32. }
    33. @Override
    34. public void run() {
    35. for (int i = 0; i < 100; i++) {
    36. try {
    37. System.out.println("消费了"+container.pop().id+"只鸡");
    38. } catch (InterruptedException e) {
    39. e.printStackTrace();
    40. }
    41. }
    42. }
    43. }
    44. //产品
    45. class Chicken{
    46. int id;
    47. public Chicken(int id) {
    48. this.id = id;
    49. }
    50. }
    51. //缓冲区
    52. class SynContainer{
    53. // 需要一个容器大小
    54. Chicken[] chickens = new Chicken[10];
    55. // 容器计算器
    56. int count = 0;
    57. // 生产者放入产品
    58. public synchronized void push(Chicken chicken) throws InterruptedException {
    59. //如果容器满了,需要等待消费者消费
    60. if(count == chickens.length){
    61. //通知消费者消费,等待生产
    62. this.wait();
    63. }
    64. //如果没有满我们就需要丢入产品
    65. chickens[count] = chicken;
    66. count++;
    67. //可以通过消费者消费了
    68. this.notifyAll();
    69. }
    70. // 消费者消费产品
    71. public synchronized Chicken pop() throws InterruptedException {
    72. //判断能否消费
    73. if(count == 0){
    74. //等待生产者生产,消费者等待
    75. this.wait();
    76. }
    77. //如果可以消费
    78. count--;
    79. Chicken chicken = chickens[count];
    80. //吃完了,通知生产者生产
    81. this.notifyAll();
    82. return chicken;
    83. }
    84. }

    大概结果:
    image.png