一共四个类 类名分别是 TestStudent -----Student -------Producer ------Consumer
个人理解 ---
只有消费者和生产者构不成消费者/生产者模式 ,想要构成该模式还需要一个缓冲区,这个缓冲区在消费者和生产
者之间类似仓库的作用
生产者类似餐厅 --- 制造菜品
缓冲区类似仓库 --- 储存数据/信息/菜品
消费者类似食客 --- 吃掉菜品/就是处理数据
public class TestStudent {
public static void main(String[] args) {
Student student = new Student();
Producer p1 = new Producer("j1", 50, student);
Producer p2 = new Producer("j2", 50, student);
Consumer c1 = new Consumer("x1", 30, student);
Consumer c2 = new Consumer("x2", 40, student);
p1.start();
p2.start();
c1.start();
c2.start();
}
}
主要写在Student类里面
public class Student {
public static final int MAX_COUNT = 100; //最大储藏值
private int currentCount; //当前库存量
public String name = "陈虎";
public int age = 200;
public String sex = "女";
private Lock lock = new ReentrantLock(); //创建锁对象
private Condition condition1 = lock.newCondition(); //得到锁的监听对象,可以对锁进行操作
private Condition condition2 = lock.newCondition(); //得到锁的监听对象,可以对锁进行操作
//生产者负责为student对象赋值
public void produce(int count) {
lock.lock(); //加锁
try {
while (count + currentCount > MAX_COUNT ) {
System.out.println(Thread.currentThread().getName() + "要赋值" + ",将会超过最大储存值,暂停赋值");
try {
condition1.await(); //当前线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//满足生产条件,执行生产任务
currentCount += count;
System.out.println(
Thread.currentThread().getName() + "赋值了" + count + "个" +"---"+ name + "--" + age + "--" + sex + ",当前库存量为" + currentCount);
//通知生产者
condition2.signalAll();
} finally {
lock.unlock();
}
}
//消费者来打印
public void consume(int count) {
lock.lock(); //加锁
try {
while(count > currentCount) {
System.out.println(Thread.currentThread().getName() + "需要打印" + count + "个" +"---"+ name + "--" + age + "--" + sex + ",当前库存量为" + currentCount + ",不够打印,暂停消费任务");
try {
condition2.await(); //当前线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//满足消费条件
currentCount -= count;
System.out.println(Thread.currentThread().getName() + "赋值了" + count + "个" +"---"+ name + "--" + age + "--" + sex + ",当前库存量为" + currentCount);
//通知生产者
condition1.signalAll();
} finally {
lock.unlock();
}
}
}
//生产者 Producer
public class Producer extends Thread {
private int count;
private Student student;
public Producer(String name,int count, Student student) {
super(name);
this.count = count;
this.student = student;
}
@Override
public void run() {
while(true) {
student.produce(count);
}
}
}
//消费者 Consumer
public class Consumer extends Thread {
private int count;
private Student student;
public Consumer(String name,int count, Student student) {
super(name);
this.count = count;
this.student = student;
}
@Override
public void run() {
while (true) {
student.consume(count);
}
}
}
以上内容如果帮到你了,我会很开心的
如果有什么错误,请评论指出,不胜感激