import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class ConsumerProducer {
private static Buffer buffer = new Buffer();
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new ProducerTask());
executor.execute(new ConsumerTask());
executor.shutdown();
}
private static class ProducerTask implements Runnable {
@Override
public void run() {
try {
int i = 1;
while (true) {
System.out.println("Producer writes \t" + i);
buffer.write(i ++);
Thread.sleep((int)(Math.random() * 10000));
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
private static class ConsumerTask implements Runnable {
public void run() {
try {
while (true) {
System.out.println("\t\t\t\t\t\t\t\tConsumer reads:\t" + buffer.read());
Thread.sleep((int)(Math.random() * 10000));
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
private static class Buffer {
private static final int CAPACITY = 1;
private LinkedList<Integer> queue = new LinkedList<>();
private Lock lock = new ReentrantLock();
private Condition notEmpty = lock.newCondition();
private Condition notFull = lock.newCondition();
public void write(int value) {
lock.lock();
try {
while (queue.size() == CAPACITY) {
System.out.println("Wait for notFull conditino");
notFull.await();
}
queue.offer(value);
notEmpty.signal();
} catch (InterruptedException ex) {
ex.printStackTrace();
} finally {
lock.unlock();
}
}
public int read() {
int value = 0;
lock.lock();
try {
while (queue.isEmpty()) {
System.out.println("\t\t\t\t\t\t\t\tWait for notEmpty condition");
notEmpty.await();
}
value = queue.poll();
notFull.signal();
} catch (InterruptedException ex) {
ex.printStackTrace();
} finally {
lock.unlock();
return value;
}
}
}
}
生产者消费者模型
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:从源码分析:Java中的AQS
下一篇:python中的is与==

提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
python 生产者消费者模型 semaphore生产者消费者
Semaphore)是实现多线程同步的两种常用的手段。信号量需要初始化一个许可值,许可值可以大于0,也可以小于0,也可以等于0.
python 生产者消费者模型 Apple 信号量 System -
android 图形生产者消费者模型 生产者消费者模型死锁
*同步一般都是外层是while循环,里面是同步代码块,再里面是循环*不安全与死锁都因为在判断中出错死锁举例:package com.qianfeng.demo02;class DeadLockThread implements Runnable { private static String milk = "牛奶"; private static String bread = "面包"
android 图形生产者消费者模型 java死锁举例 生产消费者模式 System List Customer