多线程内部类 实现的生产消费模型

package com.test;

public class Demo {

    public static final int maxCount = 100;

    public int count = 0;

    // 生产
    public void produce(int num) {
        new Thread(new Runnable() {
            public void run() {
                synchronized (this) {
                    if (count + num > 100) {
                        System.out.println("count====" + count);
                        try {
                            wait();  //超出最大数量 等待
                        }
                        catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("produce 仓库" + count);
                    count = count + num;
                    System.out.println("produce 当前" + count);
                    notifyAll();  // 唤醒所有等待线程
                }
            }
        }).start();

    }
    //消费
    public void consume(int num) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    if (num > count) {
                        System.out.println("count====" + count);
                        try {
                            wait(); //最大数量不足  等待
                        }
                        catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("consume 仓库" + count);
                    count = count - num;
                    System.out.println("consume 当前" + count);
                    notifyAll();  // 唤醒所有等待线程
                }

            }
        }).start();

    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.produce(30);
        demo.produce(20);
        demo.consume(50);
        demo.consume(10);
        demo.produce(50);
        demo.produce(50);

        demo.consume(50);
        demo.consume(10);
        demo.consume(20);
        demo.consume(50);
        demo.consume(50);
    }
}

输出结果 :
produce 仓库0
produce 当前30
produce 仓库30
produce 当前50
consume 仓库50
consume 当前0
count====0
produce 仓库0
produce 当前50
produce 仓库50
produce 当前100
consume 仓库100
consume 当前50
consume 仓库50
consume 当前40
consume 仓库40
consume 当前20
count====20
count====20

 

你可能感兴趣的:(多线程,多线程,内部类,生产消费模型)