使用join和notifyAll實現經典的生產者消費者模型


package com.zjw;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 生產者消費者問題
 */
public class JoinNotifyAllTest {

  static class MyContainer<T> {

    private List<T> container = new LinkedList<>();
    private Integer maxSize;
    private Integer size = 0;

    MyContainer(Integer maxSize) {
      this.maxSize = maxSize;
    }

    public synchronized void put(T t) throws InterruptedException {
      if (size < maxSize) {
        container.add(t);
        size++;
        System.out.println("+生產: " + t + ", current size: " + size);
        this.notifyAll();
      } else {
        System.out.println("+++生產者等待...");
        this.wait();
      }
    }

    public synchronized void get() throws InterruptedException {
      if (size == 0) {
        System.out.println("---消費者等待...");
        this.wait();
      } else {
        T tmp = container.remove(0);
        size--;
        System.out.println("-消費: " + tmp + ", current size: " + size);
        this.notifyAll();
      }
    }
  }

  public static void main(String[] args)  {
    MyContainer<Integer> container = new MyContainer<>(5);
    Random random = new Random();
    // 生產者 5個
    for (int i = 0; i < 5; i++) {
      new Thread(() -> {
        while (true) {
          try {
            TimeUnit.MILLISECONDS.sleep(random.nextInt(5000));
            container.put(random.nextInt(10000));
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }

      }).start();
    }
    // 消費者 5個
    for (int i = 0; i < 5; i++) {
      new Thread(() -> {
        while (true) {
          try {
            TimeUnit.MILLISECONDS.sleep(random.nextInt(5000));
            container.get();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }).start();
    }
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章