编程语言
首页 > 编程语言> > java多线程之消费生产模型

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();
    }
}

标签:java,printStackTrace,模型,InterruptedException,TVCount,Warehouse,warehouse,多线程,pub
来源: https://www.cnblogs.com/wsilj/p/13544274.html