用 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 ...
随机推荐
- RAID各种级别详细介绍
独立硬盘冗余阵列(RAID, Redundant Array of Independent Disks),旧称廉价磁盘冗余阵列(RAID, Redundant Array of Inexpensive ...
- 转 Configuring Relationships with the Fluent API
http://msdn.microsoft.com/zh-cn/data/jj591620 Configuring a Required-to-Optional Relationship (One-t ...
- Servlet(6)—HttpServletRequest接口和HttpServletResponse接口
HttpServletRequest接口和HttpServletResponse接口是继承ServletRequest和ServletResponse接口,是他们的子接口,但是我们在程序中进程看到Se ...
- pygame-KidsCanCode系列jumpy-part14-背景音乐及音效
没有音乐和音效的游戏是没有灵魂的,这回讲解如何处理背景音乐及跳跃音效.加载music及sound的方法,之前已经写过,见:pygame 笔记-8 背景音乐&子弹音效 . 先介绍一个很棒的生成各 ...
- spring跨域问题
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Co ...
- 倾斜摄影数据OSGB进入到ArcGIS平台相关问题小结
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/zglybl/article/details/75252288 随着倾斜摄影技术的发展,大家 ...
- AlexNet总结
https://blog.csdn.net/Rasin_Wu/article/details/80017920 https://blog.csdn.net/chaipp0607/article/det ...
- SeaweedFS的配置使用
SeaweedFS是一个简单并且高度可扩展的分布式文件系统,可以存储数十亿的文件并且快速获得文件,特别适合于有效处理小文件,这里我们简称为weed,weed的主节点不管理文件元数据而是仅管理文件卷,这 ...
- C++ delegate的几种方法
https://stackoverflow.com/questions/9568150/what-is-a-c-delegate You have an incredible number of ch ...
- 【ASP.NET Core】EF Core - “影子属性”
有朋友说老周近来博客更新较慢,确实有些慢,因为有些 bug 要研究,另外就是老周把部分内容转到直播上面,所以写博客的内容减少了一点. 老周觉得,视频直播可能会好一些,虽然我的水平一般,不过直播时,老周 ...