多线程-老板顾客线程juc-lock锁

package com.itheima.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class A {

    public static void main(String[] args) {
        Catch c = new Catch();
        new Thread(()->{for(int i = 0; i < 20; i++) c.push(new Chicken(i));}, "老板").start();
        new Thread(()->{for(int i = 0; i < 20; i++) c.eat();}, "顾客").start();

    }
}


class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}


class Catch{
    int count = 0;
    Chicken[] chickens = new Chicken[10];
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();


    public void push(Chicken chicken) {
        lock.lock();
        try {
            //业务代码
            while (count != 0) {//有我就不做
                condition.await();
            }
            if(count < chickens.length) {
                chickens[count] = chicken;
                count++;
            }

            System.out.println(Thread.currentThread().getName()+"正在做第"+chicken.id+"只鸡");
            condition.signal();//通知顾客线程

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void eat() {
        lock.lock();
        try {
            //业务代码
            while (count == 0) {//没有我就做
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"正在吃第"+chickens[--count].id+"只鸡");
            condition.signal();//通知老板线程

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }



}




在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值