生产者消费者之 wait / notify
2015-09-07 15:42
435 查看
package com.wjxie.wait.notify;
public class Producer extends Thread {
public Producer(String name) {
super(name);
}
@Override
public void run() {
while (true) {
synchronized (Main.queue) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (Main.queue.size() == Main.MAX_SIZE) {
try {
Main.queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Item item = new Item();
Main.queue.offer(item);
// 生产一次之后,立马释放锁。一方面让消费者消费,另一方面让其他生产者生产。
Main.queue.notify();
System.out.println(this.getName() + " produce " + item);
}
}
}
}
}
package com.wjxie.wait.notify;
public class Consumer extends Thread {
public Consumer(String name) {
super(name);
}
@Override
public void run() {
while (true) {
synchronized (Main.queue) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (Main.queue.size() == 0) {
try {
Main.queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Item item = Main.queue.poll();
// 消费一次之后,立马释放锁。一方面让生产者生产,另一方面让其他消费者消费。
Main.queue.notify();
System.out.println(this.getName() + " consume " + item);
}
}
}
}
}
package com.wjxie.wait.notify;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
// 最大容量
public static final int MAX_SIZE = 100;
// 容器,兼作排它锁
public static Queue<Item> queue = new LinkedList<Item>();
public static void main(String[] args) {
Thread p = new Producer("[P]");
Thread p2 = new Producer("[P2]");
Thread c = new Consumer("[C]");
Thread c2 = new Consumer("[C2]");
p.start();
p2.start();
c.start();
c2.start();
}
}
阅读更多
package com.wjxie.wait.notify;
public class Item {
private int id;
public Item() {
id = ID.getID();
}
@Override
public String toString() {
return "Item[" + id + "]";
}
static class ID {
private static int id = 0;
public static int getID() {
return ++id;
}
}
}
相关文章推荐
- 使用wait/notify实现生产者消费者
- java多线程15 :wait()和notify() 的生产者/消费者模式
- ImportNew 首页所有文章资讯Web架构基础技术书籍教程我要投稿更多频道 » 如何在 Java 中正确使用 wait, notify 和 notifyAll – 以生产者消费者模型为例
- 多线程--生产者消费者问题(wait和notify方法)
- 生产者消费者 wait()。 notify()
- 生产者与消费者 & wait()& notify()
- 多线程五,线程间通信3,wait、notify,notifyAll方法,生产者和消费者问题(14,毕向东老师)
- 【Java】线程wait() notify()通信 实现生产者 消费者问题
- 使用wait/notify模拟生产者和消费者
- 生产者消费者例子-采用wait()和notify()
- java多线程同步(wait、notify)生产者消费者简单示例
- 如何在 Java 中正确使用 wait, notify 和 notifyAll – 以生产者消费者模型为例
- Java多线程之~~~~使用wait和notify实现生产者消费者模型
- 生产者-消费者模式 系列 之一 Sychronized,Notify,Wait 篇
- 如何在 Java 中正确使用 wait, notify 和 notifyAll – 以生产者消费者模型为例
- 如何在 Java 中正确使用 wait, notify 和 notifyAll – 以生产者消费者模型为例
- 线程学习二,notify和wait实现消费者-生产者同步问题
- 学习笔记7:wait(),notify()与notifyAll()及消费者生产者小案例
- 生产者与消费者模式-阻塞 wait,notify
- java wait notifyAll 生产者 消费者 BlockingDeque