简单生产者-消费者

109 阅读1分钟

public static void main (String args[])

{

Queue<ESFProductPackageInfo> queue = new ArrayDeque<>();
for(int i=0 ;i<10;i++){    
new Thread(new producer(queue,10)).start();    
new Thread(new resume(queue,10)).start();
}

}

public class producer implements Runnable {
    private int maxCapacity;
    private Queue<ESFProductPackageInfo> queue;

    public producer(Queue queue, int maxCapacity) {
        this.queue = queue;
        this.maxCapacity = maxCapacity;
    }

    @Override
    public void run() {

        synchronized (queue) {
            while (queue.size() == maxCapacity) {
                try {
                    System.out.println("生产者" + Thread.currentThread().getName() + "等待中... Queue 已达到最大容量,无法生产");
                    wait(1000);
                    System.out.println("生产者" + Thread.currentThread().getName() + "退出等待");

                } catch (Exception e) {

                }
            }

            if (queue.size() == 0) {
                queue.notifyAll();
            }
            ESFProductPackageInfo esf = new ESFProductPackageInfo();
            Random random = new Random();
            esf.setProductJson(String.valueOf(random.nextInt()) + "号产品");
            queue.offer(esf);
            System.out.println("生产者生产了" + esf.getProductJson());
        }
    }

public class resume implements Runnable {
    private Queue<ESFProductPackageInfo> queue;
    private int maxCapacity;

    public resume(Queue queue, int maxCapacity) {
        this.queue = queue;
        this.maxCapacity = maxCapacity;
    }

    public void run() {
        while (queue.isEmpty()) {
            try {
                System.out.println("消费者" + Thread.currentThread().getName() + "等待中... Queue 已缺货,无法消费");
                wait(1000);
                System.out.println("消费者" + Thread.currentThread().getName() + "退出等待");

            } catch (Exception e) {

            }
        }
        if (queue.size() == maxCapacity) {
            queue.notifyAll();
        }
        ESFProductPackageInfo esf = queue.poll();
        System.out.println("消费者消费了" + esf.getProductJson());
    }

}