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();
}
}
}
多线程-老板顾客线程juc-lock锁
最新推荐文章于 2021-09-02 15:22:36 发布