使用synchronized实现生产者消费者模型案例

生产者

使用synchronized实现生产者消费者模型案例
生产者代码:

public class Produce implements Runnable {
    Product product;
    public Produce(Product product){
        this.product=product;

    }
    @Override
    public void run() {

        while (true){
            product.push();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

消费者代码

public class Comsuer implements Runnable {
    Product product;
    public Comsuer(Product product){
        this.product = product;
    }
    @Override
    public void run() {
        while (true){
            product.take();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

商品代码

public class Product {
    final int MAX_NUMBER = 10;
    private int max;

    public synchronized void push() {
        while (max >= MAX_NUMBER) {
            try {
                System.out.println(Thread.currentThread().getName() + "生产过剩,当前:" + max);
                this.wait();
            } catch (Exception e) {

            }
        }
        this.max++;
        System.out.println(Thread.currentThread().getName() + "生产+1,当前:" + max);
        notifyAll();
    }

    public synchronized void take() {
        while (max <= 0) {
            try {
                System.out.println(Thread.currentThread().getName() + "消费已完,当前:" + max);
                this.wait();
            } catch (Exception e) {
            }
        }
        this.max--;
        System.out.println(Thread.currentThread().getName() + "消费-1,当前:" + max);
        notifyAll();
    }
}

Main方法

public class Main {



    public static void main(String[] args) {
        System.out.println("Hello World!");
        Product product = new Product();
        Comsuer comsuer = new Comsuer(product);
        Produce produce = new Produce(product);
        new Thread(produce).start();
        new Thread(produce).start();
        new Thread(produce).start();
        new Thread(produce).start();
        new Thread(produce).start();
        new Thread(produce).start();
        new Thread(produce).start();
        new Thread(comsuer).start();
        new Thread(comsuer).start();
        new Thread(comsuer).start();

    }
}

结果:

Hello World!
Thread-0生产+1,当前:1
Thread-1生产+1,当前:2
Thread-2生产+1,当前:3
Thread-3生产+1,当前:4
Thread-7消费-1,当前:3
Thread-5生产+1,当前:4
Thread-6生产+1,当前:5
Thread-4生产+1,当前:6
Thread-8消费-1,当前:5
Thread-9消费-1,当前:4
Thread-5生产+1,当前:5
Thread-3生产+1,当前:6
Thread-0生产+1,当前:7
Thread-2生产+1,当前:8
Thread-1生产+1,当前:9
Thread-7消费-1,当前:8

猜你喜欢

转载自blog.csdn.net/cckkpp/article/details/88594619