java多线程之消费生产模型

需求:要求仓库最大容量为4,且一共只生产20台电视机,下面的代码只适用于一个生产者一个消费者,有没有大佬提点建议怎么改成一对多或多对多不会出现死锁情况

class Warehouse {

    private int TVCount = 0;

    // 生产

    public synchronized void produce() {
        if (TVCount < 4) {
            TVCount++;
            System.out.println(Thread.currentThread().getName() + "开始生产第 " + TVCount + " 台电视");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            super.notify();

        } else {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 消费

    public synchronized void consume() {

        if (TVCount > 0) {
            System.out.println(Thread.currentThread().getName() + "开始消费第 " + TVCount + " 台电视");
            TVCount--;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            super.notify();
        } else {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}
class Productor extends Thread {

    private Warehouse warehouse;

    public Productor(Warehouse warehouse) {
        this.warehouse = warehouse;
    }

    @Override
    public void run() {
        System.out.println("开始生产电视机");
        for (int i = 0; i < 20; i++) {
            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            warehouse.produce();
        }
    }
}
class Consumer extends Thread {
    private Warehouse warehouse;

    public Consumer(Warehouse warehouse) {
        this.warehouse = warehouse;
    }

    @Override
    public void run() {
        System.out.println("开始消费新产品");
        for (int i = 0; i < 20; i++) {
            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            warehouse.consume();
        }
    }
}
public class ThreadExer5 {
    public static void main(String[] args) {
        Warehouse warehouse = new Warehouse();

        Productor t1 = new Productor(warehouse);
//        Productor t3 = new Productor(warehouse);
        Consumer t2 = new Consumer(warehouse);

        t1.setName("生产者1");
        t2.setName("消费者1");
//        t3.setName("生产者2");

        t1.start();
        t2.start();
//        t3.start();
    }
}
posted @ 2020-08-22 08:25  wsilj  阅读(316)  评论(1编辑  收藏  举报