|
楼主 |
发表于 2020-11-3 09:55:52
|
显示全部楼层
package com.example.demo.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProdConsumerDemo02 {
public static void main(String[] args) {
ShareEntry shareEntry = new ShareEntry(3000);
// 15 个生产者
for (int i = 0; i < 15; i++) {
new Thread(() -> {
while (true) {
shareEntry.increment();
}
}).start();
}
// 30个消费者
for (int i = 0; i < 30; i++) {
new Thread(() -> {
while (true) {
shareEntry.deIncrement();
}
}).start();
}
}
private static class ShareEntry {
private int shareNumber;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private ShareEntry(int shareNumber) {
this.shareNumber = shareNumber;
}
private void increment() {
try {
lock.lock();
shareNumber++;
System.out.println("生产者工作, 当前剩余资源:" + shareNumber);
// 资源增加后可以唤醒消费者
condition.signalAll();
} finally {
lock.unlock();
}
}
private void deIncrement() {
try {
lock.lock();
while (shareNumber == 0) {
condition.await();
}
shareNumber--;
System.out.println("消费者工作, 当前剩余资源:" + shareNumber);
// 因为生产者不会阻塞, 因此不需要唤醒生产者
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
|
|