ReentranLock 实现生产者消费者
static ReentrantLock lock = new ReentrantLock();
static Condition empty = lock.newCondition();
static Condition full = lock.newCondition();
static volatile int size = 0;
static final int max_size = 10;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Consumer().start();
new Producer().start();
}
}
static class Consumer extends Thread {
@SneakyThrows
@Override
public void run() {
lock.lock();
while (size == 0) {
empty.await();
}
System.out.println("消费"+size);
size--;
full.signal();
lock.unlock();
}
}
static class Producer extends Thread {
@SneakyThrows
@Override
public void run() {
lock.lock();
while (size == max_size) {
full.await();
}
size++;
System.out.println("生产"+size);
empty.signal();
lock.unlock();
}
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 程序员小航
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果