问题:利用队列+线程手写生产者和消费者?
public class Thread1 {
static volatile LinkedBlockingQueue<Integer> queue=new LinkedBlockingQueue<>(5);
@SneakyThrows
public static void main(String[] args) {
new Thread(new Productor()).start();
new Thread(new Consumer()).start();
}
// 生产者
static class Productor implements Runnable{
@Override
public void run() {
productor(queue);
}
@SneakyThrows
public static void productor(LinkedBlockingQueue<Integer> queue){
// 有10个待生产的数据
for (int i = 0; i < 10; i++) {
synchronized (queue){
// 条件有限 一次只能生产5个
if(queue.size()==5){
// 满了5个 之后 剩余的待生产个数都在等在着被生产
// 在挂起的时候一定要获取到对象锁,没有获取到对象锁会报异常
queue.wait();
}
// 空闲则生产元素
queue.add(i);
System.out.println("我在生产元素,哈哈哈");
queue.notifyAll();
}
}
}
}
// 消费者
static class Consumer implements Runnable{
@Override
public void run() {
consumer(queue);
}
@SneakyThrows
public static void consumer(LinkedBlockingQueue<Integer> queue){
// 有10个待消费
for (int i = 0; i < 10; i++) {
synchronized (queue){
if(queue.size()==0){
queue.wait();
}
queue.take();
System.out.println("我在消费元素,哈哈哈");
queue.notifyAll();
}
}
}
}
}
来源:CSDN
作者:一只在程序中迷茫的喵
链接:https://blog.csdn.net/qq_36934544/article/details/104796195