在同步块中调用 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引擎的常用倒计时

    直接上代码, private timeControl() { let timer: egret.Timer = segret.Timer(); timer.addEventListener(egret ...

  2. 列表去重几种方法 python

    1.方法一: >>> a=[1,1,2,2,3,3] >>> b=[] >>> for i in a: ...     if i not in b ...

  3. jmeter接口测试实例1-添加学生信息

    jmeter实例1:添加学生信息 进入jmeter,添加线程组改名称为添加学生信息(为了好区分接口),添加http请求,输入IP,方法,路径,在body data中输入json串,同上面postman ...

  4. ionic2 处理android硬件返回按钮

    问题 注册安卓硬件返回按钮事件是必须的,因为用户不小心点击了返回按钮就退出app体验很不好,所以有几种方法: 1.实现按返回键最小化应用(最小化应用需要装cordova-plugin-appminim ...

  5. linux之测试硬盘速度篇

    作业三:dd命令测试硬盘速度 [root@localhost 桌面]# dd if=/dev/sdc2 of=/a.txt bs=2M count=2 记录了0+1 的读入 记录了0+1 的写出 10 ...

  6. C_求质数

    质数:质数(prime number)又称素数,有无限个.质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数,这样的数称为质数. 题设:输入一个大于1的自然数,求出从2到该数之间所有的质数 ...

  7. 12 week blog

    调用一个地图(百度地图)API(定位) 到网站: 1.调用API的js : <script type="text/javascript" src="https:// ...

  8. Kubernetes Ingress 学习

    Kubernetes 中暴露服务的方式有三种 Loadbalancer 这种方式往往需要云供应商支持,或者本地F5等设备支持 NodePort 这种方式调用方通过NodeIP:NodePort 的方式 ...

  9. golang dlv 远程调试

    因为不知道delvel 是如何设置源码的,本地编译的上传到服务器上,服务器要调试看不到源码,很是忧伤,所以干脆使用远程调试吧: 在服务器上 ps x|grep game 查找到gameserver的进 ...

  10. .Net:System.Guid

    ylbtech-.Net:System.Guid 1.返回顶部 1.public static Guid NewGuid(); // // 摘要: // 初始化 System.Guid 结构的新实例. ...