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();
}
}
全部评论 (暂无评论)
info 还没有任何评论,你来说两句呐!