import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static final Queue<Integer> message = new LinkedList<>();
public static ReentrantLock lock = new ReentrantLock();
public static Condition writeable = lock.newCondition();
public static Condition readable = lock.newCondition();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("生产者开始运行");
for (int i = 0; i <= 20; i++) {
lock.lock();
try {
System.out.println("生产者取得队列所有权=======");
while (message.size() >= 10) {
try {
System.out.println("队列中已经有10个消息,生产者阻塞");
writeable.await();
System.out.println("队列恢复可写,生产者唤醒");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
if (i == 20) {
System.out.println("生产者产生结束信号");
message.add(-1);
System.out.println("生产者运行结束");
readable.signal();
break;
} else {
System.out.println("生产者向队列写入 " + i);
message.add(i);
System.out.println("唤醒消费者");
readable.signal();
}
} finally {
lock.unlock();
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("消费者开始运行");
while (true) {
lock.lock();
System.out.println("消费者取得队列所有权=======");
try {
while (message.isEmpty()) {
try {
System.out.println("消费者等待队列可读");
readable.await();
System.out.println("消费者恢复可读");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
Integer a = message.poll();
if (a == -1) {
System.out.println("消费者读到结束信号,消费者结束");
break;
}
System.out.println("从队列读出 " + a);
System.out.println("唤醒生产者");
writeable.signal();
} finally {
lock.unlock();
}
}
System.out.println("消费者运行结束");
}
});
thread1.start();
thread2.start();
}
}
标签:Java,生产者,lock,模型,System,println,new,public,out
From: https://www.cnblogs.com/DCFV/p/18436643