生产者和消费者的简单实现

生产者和消费者

概述

生产者和消费者是在大学java课程中刚开始讲线程的时候的老师讲的一个经典的一个问题,假如一个手工艺人10分钟制作1个手工品,当消费者去进行购买的时候怎么去保证购买成功,当消费者购买完了生产的手工品,还能继续去购买吗?作为生产者的手工艺人又是什么状态?手工艺人制作完手工品之后,消费者又是什么状态?当有100个手工品的时候,怎么去保证多个消费者(多线程)买不到同一个商品。

代码实现

这种实现是使用synchronized 关键字去实现的,对资源进行加锁,生产者还是消费者都会对资源进行判断,例如消费者消费的时候没有资源了执行notify唤醒生产者线程。生产者生产完,使用notifyAll唤醒消费者线程。

public class Demo2 {

    public static void main(String[] args) {
        List list = new ArrayList();
        Thread thread = new Thread(new Productor(list));
        Thread thread1 = new Thread(new Consumer(list));

        thread.start();
        thread1.start();
    }
}


class Consumer implements  Runnable{
    private List list;// 生产的公共资源

    public Consumer(List list){
        this.list = list;
    }

    @Override
    public void run() {

        while(true){
            synchronized (list) {
                if (list.size() < 1) {//list中没有元素
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "  " + list.remove(0));
                list.notify();//唤醒生产者线程
            }
        }
    }
}

class Productor implements Runnable{

    private List list;// 生产的公共资源

    public Productor(List list){
        this.list = list;
    }

    @Override
    public void run() {

        while(true){
            Random random = new Random();
            synchronized(list){
                if(list.size() >0 ){
                    try {
                        list.wait(); //这个线程等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                list.add("苹果手机"+random.nextInt(100));
                System.out.println(Thread.currentThread().getName()+"  "+list.get(0));
                list.notifyAll(); //通知消费者
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值