用 wait-notify 写一段代码来解决生产者-消费者问题
在同步块中调用 wait() 和 notify()方法,如果阻塞,通过循环来测试等待条件。请参考答案中的示例代码。
【生产者】
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger; public class Producer implements Runnable { private final Vector sharedQueue;
private final int SIZE; public Producer(Vector sharedQueue, int size) {
this.sharedQueue = sharedQueue;
this.SIZE = size;
} @Override
public void run() {
// 生产数据
for (int i = 0; i < 7; i++) {
System.out.println("Produced:" + i);
try {
produce(i);
} catch (InterruptedException ex) {
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
}
}
} private void produce(int i) throws InterruptedException { // wait if queue is full
while (sharedQueue.size() == SIZE) {
synchronized (sharedQueue) {
System.out.println("Queue is full " + Thread.currentThread().getName()
+ " is waiting , size: " + sharedQueue.size());
sharedQueue.wait();
}
} // producing element and notify consumers
synchronized (sharedQueue) {
sharedQueue.add(i);
sharedQueue.notifyAll();
}
}
}
【消费者】
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger; public class Consumer implements Runnable { private final Vector sharedQueue;
private final int SIZE; public Consumer(Vector sharedQueue, int size) {
this.sharedQueue = sharedQueue;
this.SIZE = size;
} @Override
public void run() {
// 消费数据
while (true) {
try {
System.out.println("Consumer: " + consume());
Thread.sleep(50);
} catch (InterruptedException ex) {
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
}
}
} private int consume() throws InterruptedException { // wait if queue is empty
while (sharedQueue.isEmpty()) {
synchronized (sharedQueue) {
System.out.println("Queue is empty " + Thread.currentThread().getName()
+ " is waiting , size: " + sharedQueue.size());
sharedQueue.wait();
}
} //otherwise consume element and notify waiting producer
synchronized (sharedQueue) {
sharedQueue.notifyAll();
return (Integer) sharedQueue.remove(0);
}
}
}
【测试函数】
import java.util.Vector;
public class ProducerConsumerSolution {
public static void main(String[] args) {
Vector sharedQueue = new Vector();
int size = 4;
Thread prodThread = new Thread(new Producer(sharedQueue, size), "Producer");
Thread consThread = new Thread(new Consumer(sharedQueue, size), "Consumer");
prodThread.start();
consThread.start();
}
}
运行结果:
Produced:0
Queue is empty Consumer is waiting , size: 0
Produced:1
Consumer: 0
Produced:2
Produced:3
Produced:4
Produced:5
Queue is full Producer is waiting , size: 4
Consumer: 1
Produced:6
Queue is full Producer is waiting , size: 4
Consumer: 2
Consumer: 3
Consumer: 4
Consumer: 5
Consumer: 6
Queue is empty Consumer is waiting , size: 0
用 wait-notify 写一段代码来解决生产者-消费者问题的更多相关文章
- 用 wait-notify 写一段代码来解决生产者-消费者问题?(答案)
请参考答案中的示例代码.只要记住在同步块中调用 wait() 和 notify()方法,如果阻塞,通过循环来测试等待条件.
- 用 wait-notify 写一段代码来解决生产者-消费者问题?
只要记住在同步块中调用 wait() 和 notify()方法,如 果阻塞,通过循环来测试等待条件.
- javascript 写一段代码,判断一个字符串中出现次数最多的字符串,并统计出现的次数
javascript 写一段代码,判断一个字符串中出现次数最多的字符串,并统计出现的次数 function test(){ var bt = document.getElementById(" ...
- Java 中 wait, notify 和 notifyAll的正确使用 – 以生产者消费者模型为例
如何使用Wait 尽管关于wait和notify的概念很基础,它们也都是Object类的函数,但用它们来写代码却并不简单.如果你在面试中让应聘者来手写代码,用wait和notify解决生产者消费者问题 ...
- 假设写一段代码引导PC开机这段代码是 ? Here is a tiny "OS" :-D
Hello world -- OS 我找到了华科绍志远博士的相关代码,发现他依据MIT的JOS的boot.S 稍作改动.然后单独剥离出来,能够非常好玩~ 资料下载地址: http://download ...
- 用for循环写这段代码
之前用while循环写了一段代码,现在改为用for循环来写,代码如下: hongtao_age = 38 for i in range(5): guess_age = int(input(" ...
- JavaScript-navigator_userAgent-编写一段代码能够区分浏览器的主流和区分
1 userAgent:包含浏览器名称和版本号的字符串 <!DOCTYPE html> <html> <head lang="en"> < ...
- 写一段代码在遍历 ArrayList 时移除一个元素?
该问题的关键在于面试者使用的是 ArrayList 的 remove() 还是 Iterator 的 remove()方法.这有一段示例代码,是使用正确的方式来实现在遍历的过程中移 除元素,而不会出现 ...
- PHP写一段代码,确保多个进程同时写入一个文件成功
这个需求是在软件设计过程常见的加锁.学计算机的同学都应该知道,这个是在<计算机操作系统>课程上有这个知识点.主要要考虑的是进程的同步,也就是进程对资源的互斥访问.OK,用程序说话吧! &l ...
随机推荐
- echarts动态添加数据
数据异步加载 EChart中实现异步数据的更新非常简单,在图表初始化后不管任何时候只要通过 jQuery 等工具异步获取数据后通过 setOption 填入数据和配置项就行. 绑定数据的方式有两种,一 ...
- oval-and-rectangle
oval-and-rectangle Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Other ...
- HDU 5985 Lucky Coins 数学
Lucky Coins 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5985 Description Bob has collected a lot ...
- OpenXC : Any updates on plans for IOS?
OpenXC : Any updates on plans for IOS? Hi Thomas, We're actively investigating this as we'd love to ...
- 什么是crf
什么是crf 利用crf++进行实体识别的流程 确定标签体系: 确定特征模板文件: 处理训练数据文件: 模型训练. 确定标签体系 大部分情况下,标签体系越复杂准确度也越高,但相应的训练时间也会增加.因 ...
- jQuery 选择同时包含两个或多个class的元素的实现方法
Jquery选择器 多个 class属性参照以下案例 <element class="a b good list card"> 1. 交集选择: $(".a. ...
- angular 2 - 006 change detection 脏治检查 - DC
ANGULAR CHANGE DETECTION EXPLAINED 引发脏治检查有三种方式: Events - click, submit, - XHR - Fetching data from a ...
- react diff 原理
(1) 把树形结构按照层级分解,只比较同级元素.(2) 列表结构的每个单元添加唯一的 key 属性,方便比较.(3) React 只会匹配相同 class 的 component(这里面的 class ...
- JSP简单练习-猜字母游戏
<!-- guessCharExample.jsp --> <%@ page contentType="text/html; charset=gb2312" %& ...
- Django 用户登陆访问限制 @login_required
#用户登陆访问限制 from django.http import HttpResponseRedirect #只有登录了才能看到页面 #设置方法一:指定特定管理员才能访问 def main(requ ...