java多线程经典案例:生产者和消费者实现的两种方式

本文详细探讨了Java中实现生产者消费者问题的两种经典方法:一是使用`synchronized`同步关键字,二是采用`Lock`锁机制。通过对这两种方式的对比分析,帮助开发者更好地理解和应用多线程技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一 synchronized同步函数:

    public static void main(String[] args) {
        Product product = new Product();
//        让他们指定同一个对象,同一个锁
        Producer producer = new Producer(product);
        Saler saler = new Saler(product);
//        让他们加入多线程
        Thread td1 = new Thread(producer);
        Thread td2 = new Thread(saler);
//        启动多线程
        td1.start();
        td2.start();
    }
//产品
class Product{
    private int id;
    private String name;
    private boolean fal;
    private int count;

    public boolean isFal() {
        return fal;
    }

    public void setFal(boolean fal) {
        this.fal = fal;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public synchronized void saling(){
        //                当他是true的时候 休息
        if(!this.isFal()){
            try {
//                        释放cup和锁
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
//                    买产品
            System.out.println(Thread.currentThread().getName()+"购买:"+this.getName()+this.getId());
            this.setFal(false);
//                    激活
            this.notify();
        }
    }
    public synchronized void Prling(){
        //                当它是false的时候进入if
        if(this.isFal()){
            try {
//                        释放cpu的执行权和释放锁
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
//                    卖产品
            this.setName("电脑");
            this.setId((++count));
            System.out.println(Thread.currentThread().getName()+"卖:"+this.getName()+this.getId());
            this.setFal(true);
            //生产完了唤醒一个线程
            this.notify();
        }
    }
}


//买家
class Saler implements Runnable{
    private Product p;
    public Saler(){}
//    需要共同的锁
    public Saler(Product p){
        this.p = p;
    }

    @Override
    public void run() {
//        买的代码
        while(true){
                p.saling();
        }
    }
}

//卖者
class Producer implements Runnable{
    private Product p;
    private int count;
    public Producer(Prodct prodct){}
    public Producer(Product p){
        this.p = p;
    }
    @Override
    public void run() {
//            生产的代码
        while(true){
//           上锁: 保证是同一个对象
                p.Prling();
        }
    }
}

方式二 lock锁:

public static void main(String[] args) {
    Prodct prodct = new Prodct();
    production1 producer = new production1(prodct);
    consumer1 consumer1 = new consumer1(prodct);
    Thread td1 = new Thread(producer);
    Thread td2 = new Thread(consumer1);
    td1.start();
    td2.start();
}
//产品
class Prodct1{
    private int id;
    private String name;
    private boolean fal;
    private int co;
    public boolean isFal() {
        return fal;
    }

    public void setFal(boolean fal) {
        this.fal = fal;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    Lock lock = new ReentrantLock();
    Condition cd_p = lock.newCondition();
    Condition cd_s = lock.newCondition();
    //    同步函数
    public  void prsuo(){
        lock.lock();
//        最初的时候是false 所以会先生产
        if(this.isFal()){
            try {
                cd_p.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            this.setFal(true);
            this.setName("电脑");
            this.setId((++co));
            System.out.println(Thread.currentThread().getName()+"生产:"+getName()+getId());
//            唤醒所有的线程
            cd_s.notifyAll();
        }
        lock.unlock();
    }
    //    消费者的同步函数
    public void sesuo(){
        lock.lock();
        if(!this.isFal()){
            try {
                cd_s.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            this.setFal(false);
            System.out.println(Thread.currentThread().getName()+"消费:"+getName()+getId());
//            唤醒所有的线程
            cd_p.notifyAll();
        }
        lock.unlock();
    }
}
//生产者
class production1 implements Runnable{
    private Prodct p;

    public production1(Prodct p){
        this.p = p;
    }
    @Override
    public void run() {
//        生产者的代码
        while(true){
            p.prsuo();
        }
    }
}
//消费者
class consumer1 implements Runnable{
    private Prodct p;
    public consumer1(Prodct p){
        this.p = p;
    }
    @Override
    public void run() {
        while(true){
            p.sesuo();
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值