在同步块中调用 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 写一段代码来解决生产者-消费者问题的更多相关文章

  1. 用 wait-notify 写一段代码来解决生产者-消费者问题?(答案)

    请参考答案中的示例代码.只要记住在同步块中调用 wait() 和 notify()方法,如果阻塞,通过循环来测试等待条件.

  2. 用 wait-notify 写一段代码来解决生产者-消费者问题?

    只要记住在同步块中调用 wait() 和 notify()方法,如 果阻塞,通过循环来测试等待条件.

  3. javascript 写一段代码,判断一个字符串中出现次数最多的字符串,并统计出现的次数

    javascript 写一段代码,判断一个字符串中出现次数最多的字符串,并统计出现的次数 function test(){ var bt = document.getElementById(" ...

  4. Java 中 wait, notify 和 notifyAll的正确使用 – 以生产者消费者模型为例

    如何使用Wait 尽管关于wait和notify的概念很基础,它们也都是Object类的函数,但用它们来写代码却并不简单.如果你在面试中让应聘者来手写代码,用wait和notify解决生产者消费者问题 ...

  5. 假设写一段代码引导PC开机这段代码是 ? Here is a tiny &quot;OS&quot; :-D

    Hello world -- OS 我找到了华科绍志远博士的相关代码,发现他依据MIT的JOS的boot.S 稍作改动.然后单独剥离出来,能够非常好玩~ 资料下载地址: http://download ...

  6. 用for循环写这段代码

    之前用while循环写了一段代码,现在改为用for循环来写,代码如下: hongtao_age = 38 for i in range(5): guess_age = int(input(" ...

  7. JavaScript-navigator_userAgent-编写一段代码能够区分浏览器的主流和区分

    1 userAgent:包含浏览器名称和版本号的字符串 <!DOCTYPE html> <html> <head lang="en"> < ...

  8. 写一段代码在遍历 ArrayList 时移除一个元素?

    该问题的关键在于面试者使用的是 ArrayList 的 remove() 还是 Iterator 的 remove()方法.这有一段示例代码,是使用正确的方式来实现在遍历的过程中移 除元素,而不会出现 ...

  9. PHP写一段代码,确保多个进程同时写入一个文件成功

    这个需求是在软件设计过程常见的加锁.学计算机的同学都应该知道,这个是在<计算机操作系统>课程上有这个知识点.主要要考虑的是进程的同步,也就是进程对资源的互斥访问.OK,用程序说话吧! &l ...

随机推荐

  1. Egret 项目文件夹配置和基本容器、动画

    Egret 项目文件夹配置和基本容器.动画: class Main extends egret.DisplayObjectContainer { //src是resource codede 缩写,所有 ...

  2. 深入理解this,bind、call

    直接看this 直接看call和bind 首先放一道题: var a={ a:'haha', getA: function(){ console.log(this.a); } } var b= { a ...

  3. C语言中字符输入问题

    先上例题,一道太水太水的题, http://acm.hdu.edu.cn/showproblem.php?pid=1170 让做一个简单的计算器.然而入坑了. #include<stdio.h& ...

  4. 微信小程序-转发

    仅供参考 1,js: onShareAppMessage(res) { return { title: '我在使用俺搜·找客户,10万+材料人都在用,就差你了', path: '/pages/inde ...

  5. python每日笔记

    9.28 查看python包路径: sys.path 9.4  sorted高级用法: >>> class Student: def __init__(self, name, gra ...

  6. .NET语言的编译过程:中间语言(IL)和即时编译器(JIT)

    .NET语言的编译分为两个阶段.首先高级语言被编译成一种称作IL的中间语言,与高级语言相比,IL更像是机器语言,然而,IL却包含一些抽象概念(比如:类.异常),这也是这种语言被称为中间语言的原因.IL ...

  7. C# Task ContinueWith的实现

    看了上一篇C# Task 是什么?返回值如何实现? Wait如何实现 我们提到FinishContinuations方法中会调用TaskContinuation实例,那么我们的ContinueWith ...

  8. Zip文件和RAR文件解压

    直接上工具类: package com.ksource.pwlp.util; import java.io.File; import java.io.FileOutputStream; import ...

  9. 【Java-JPA】让Springboot启动不检查JPA的数据源配置

    #https://stackoverflow.com/questions/24074749/spring-boot-cannot-determine-embedded-database-driver- ...

  10. 使用http load测试qps

    官网 http://acme.com/software/http_load/ 安装 wget http://acme.com/software/http_load/http_load-12mar200 ...