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

来源:互联网 发布:手机淘宝设置货到付款 编辑:程序博客网 时间:2024/06/05 18:18
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 仓库0produce 当前30produce 仓库30produce 当前50consume 仓库50consume 当前0count====0produce 仓库0produce 当前50produce 仓库50produce 当前100consume 仓库100consume 当前50consume 仓库50consume 当前40consume 仓库40consume 当前20count====20count====20 

1 0
原创粉丝点击