线程安全案例:生产者与消费者案例

假设有三个角色:生产者、消费者、服务员。生产者不停的向服务员生产商品,消费者不停的从服务员那里消费商品。如果服务员手里的商品数量大于20,就会通知生产者停止生产;如果服务员手里的商品数量小于0,就会通知消费者,停止消费。

分析:

① 线程:两个,生产者和消费者
② 共享数据:商品

代码

class Service{//服务员
    public int number = 0;//商品数量
}
class Producer implements Runnable{//生产者
    public Service service;

    public Producer(Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            product();
        }
    }

    //生产产品的方法
    public  void product() {
        synchronized (service) {
            if (service.number < 20) {
                service.number++;
                System.out.println(Thread.currentThread().getName() + "生产了第" + service.number + "个产品");
                service.notify();//每生产一个,就告知消费者,可以消费了
            } else {
                try {
                    service.wait();//产品数量大于20,停止生产
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class Customerr implements Runnable{//消费者
    public Service service;

    public Customerr(Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            customer();
        }
    }

    //消费者消费产品的方法
    public  void customer() {
        synchronized (service) {
            if (service.number > 0) {
                System.out.println(Thread.currentThread().getName() + "消费了第" + service.number + "个产品");
                service.number--;
                service.notify();//每消费一个,就告知生产者,可以生产了
            } else {
                try {
                    service.wait();//产品缺货,停止消费
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class ProduceTest {
    public static void main(String[] args) {
        Service service = new Service();
        Customerr customer = new Customerr(service);
        Producer producer = new Producer(service);
        Thread threadCustomer = new Thread(customer);
        Thread threadProducer = new Thread(producer);
        threadCustomer.setName("消费者");
        threadProducer.setName("生产者");
        threadProducer.start();
        threadCustomer.start();

    }
}

版权声明:本文为weixin_43396422原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。