java-生产者消费者模式
来源:互联网 发布:网络录相机输出黑屏 编辑:程序博客网 时间:2024/05/20 16:40
经常会有公司叫我们手撕代码,比如网易,阿里,那我们是不是该掌握下呢。下面这段代码来自《现代操作系统》进程与线程P49页。
public class ProducerConsumer { public ProducerConsumer() { } private static final int N = 100; static Producer producer = new Producer(); static Consumer consumer = new Consumer(); static Monitor monitor = new Monitor(); private static class Producer extends Thread { @Override public void run() { //你生产的对象 int item; while(true) { item = produce_item(); monitor.insert(item); } } public int produce_item() { //TODO你需要生产的对象 } } private static class Consumer extends Thread { @Override public void run() { //你打算消费的对象 int item; while(true) { item = monitor.remove(); consumer_item(item); } } private int consumer_item(int item) { // TODO Auto-generated method stub } } private static class Monitor { //存放对象的容器 LinkedList<Integer> buffer = new LinkedList<>(); int count =0; public synchronized void insert(int item) { if(count == N) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } buffer.add(item); count++; if(count == 1) { notifyAll(); } } public synchronized int remove() { if(count == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int val = buffer.getFirst(); buffer.remove(); count--; if(count == N-1) { notifyAll(); } return val; } public static void main(String[] args) { producer.start(); consumer.start(); }}
阅读全文
0 0
- Java生产者消费者模式
- 生产者消费者模式---java
- 生产者/消费者模式 (java)
- java 消费者、生产者模式
- java 生产者消费者模式
- 生产者消费者模式 JAVA
- java-生产者消费者模式
- java多线程 ----生产者消费者模式
- java生产者消费者模式代码
- Java生产者消费者模式实现
- 生产者消费者模式Java实现
- Java多线程 --- 生产者消费者模式
- Java多线程 生产者消费者模式
- 生产者消费者模式(java)
- java生产者消费者模式练习
- java之生产者消费者模式
- java多线程---生产者消费者模式
- 生产者消费者模式Java实现
- $.ajaxFileUpload is not a function
- 手动操作数据库
- a标签置灰不可点击
- 【JSTL】c:choose用法
- layer关闭当前页面
- java-生产者消费者模式
- 0731
- 框架搭建(从已有项目抽取出框架)
- 船舶的几个吨位概念
- oracle错误
- NIO入门
- 【对比】mysql 与 oracle 区别
- 面试题
- 【navicat】navicat导入导出数据库步骤