Java_生产者消费者模式
2014-03-23 22:51
309 查看
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package testdemo1; import java.util.logging.Level; import java.util.logging.Logger; class Mantou { private int id; public Mantou(int val) { this.id = val; } public String toString() { return "Mantou id: " + this.id; } } class Basket { private Mantou[] mStack = new Mantou[6]; private int index = 0; public synchronized void push(Mantou m) { while (index == mStack.length) { try { this.wait(); System.out.println("full........................!!!"); } catch (InterruptedException ex) { Logger.getLogger(Basket.class.getName()).log(Level.SEVERE, null, ex); } } this.notify(); mStack[index] = m; index++; System.out.println("add Mantou id= " + m + " and index= " + index); } public synchronized Mantou pop() { while (index == 0) { try { System.out.println("empty........................!!!"); wait(); } catch (InterruptedException ex) { Logger.getLogger(Basket.class.getName()).log(Level.SEVERE, null, ex); } } this.notify(); index--; Mantou m = mStack[index]; System.out.println("get Mantou id= " + m + " and index= " + index); return m; } } class Producer implements Runnable { private Basket brasket = new Basket(); public Producer(Basket val) { this.brasket = val; } @Override public void run() { for (int i = 0; i < 20; i++) { Mantou m = new Mantou(i); brasket.push(m); try { // Thread.sleep(Math); Thread.sleep((int) (Math.random() * 500)); } catch (InterruptedException ex) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex); } } } } class Consumer implements Runnable { private Basket brasket = new Basket(); public Consumer(Basket val) { this.brasket = val; } @Override public void run() { for (int i = 0; i < 20; i++) { Mantou m = brasket.pop(); try { Thread.sleep((int) (Math.random() * 1000)); } catch (InterruptedException ex) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } } } } public class TestDemo1 { public static void main(String[] args) { // TODO code application logic here Basket s = new Basket(); Producer producer = new Producer(s); Consumer consumer = new Consumer(s); Thread tr1 = new Thread(producer); Thread tr2 = new Thread(consumer); tr1.start(); tr2.start(); } }
相关文章推荐
- Java多线程实现消费者/生产者模式
- 设计模式-生产者与消费者Java实现
- JAVA并发实现五(生产者和消费者模式wait和notify方式实现)
- Java producer-consumer(生产者/消费者模式)
- 使用java.util.concurrent包来实现生产者和消费者模式
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现
- 线程池 生产者 消费者 模式 JAVA进阶
- Java多线程-工具篇-BlockingQueue(实现生产者和消费者模式)
- java多线程(2)-实现生产者/消费者模式
- Java多线程之并发协作生产者消费者设计模式
- Java多线程 - 实现生产者与消费者模式
- Java利用BlockingQueue实现生产者和消费者模式
- java多线程之消费者生产者模式
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现
- Java基础多线程间通讯之多生产者、多消费者模式示例:
- Java生产者-消费者模式的阻塞队列实现
- JAVA 生产者与消费者模式
- java多线程 ----生产者消费者模式
- Java并发 生产者-消费者模式
- Java实现生产者/消费者模式