生产者消费者java实现
2013-08-07 11:29
183 查看
package 线程; import java.util.LinkedList; public class 生产者消费者 { private LinkedList storeHouse = new LinkedList(); private int MAX = 10; public 生产者消费者() { } public void start() { new Producer().start(); new Comsumer().start(); } class Producer extends Thread { public void run() { while (true) { synchronized (storeHouse) { try { while (storeHouse.size() == MAX) { System.out .println("storeHouse is full , please wait"); storeHouse.wait(); } Object newOb = new Object(); if (storeHouse.add(newOb)) { System.out .println("Producer put a Object to storeHouse"); Thread.sleep((long) (Math.random() * 3000)); storeHouse.notify(); } } catch (InterruptedException ie) { System.out.println("producer is interrupted!"); } } } } } class Comsumer extends Thread { public void run() { while (true) { synchronized (storeHouse) { try { while (storeHouse.size() == 0) { System.out .println("storeHouse is empty , please wait"); storeHouse.wait(); } storeHouse.removeLast(); System.out .println("Comsumer get a Object from storeHouse"); Thread.sleep((long) (Math.random() * 3000)); storeHouse.notify(); } catch (InterruptedException ie) { System.out.println("Consumer is interrupted"); } } } } } public static void main(String[] args) throws Exception { 生产者消费者 pc = new 生产者消费者(); pc.start(); } }
相关文章推荐
- 使用java.util.concurrent包来实现生产者和消费者模式
- Java 5种方法实现生产者消费者问题与2种方法实现读者写者问题
- Java中通过wait和notify来实现生产者和消费者模式
- Java实现生产者与消费者的同步
- 生产者/消费者问题的多种Java实现方式
- java实现生产者消费者
- Java实现同步机制(生产者消费者)
- 生产者/消费者问题的多种Java实现方式
- 基于Java阻塞队列实现生产者与消费者模式
- java多线程实现生产者与消费者---经典问题
- java实现生产者与消费者(一)
- java实现生产者消费者问题
- java模拟实现生产者---消费者问题
- 生产者消费者问题之Java线程实现
- 生产者-消费者模型的java实现
- Java 线程同步问题 生产者-消费者 算法实现 -Java学习笔记(29)
- 生产者/消费者问题的多种Java实现方式
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现
- 生产者/消费者问题的多种Java实现方式
- Java实现生产者和消费者问题