java线程模拟生产者与消费者
2009-04-12 13:57
489 查看
public class ProducerConsumer { public static void main( String[] args ) { SyncStack sync = new SyncStack() ; Producer pro = new Producer( sync ) ; Consumer con = new Consumer( sync ) ; for( int i = 0 ; i < 1 ; i ++ ) { new Thread( pro , String.valueOf( i ) ).start() ; new Thread( con , String.valueOf( i )).start() ; } } } /** * 窝头堆栈 * */ class SyncStack { private Woto[] wos = new Woto[600] ; private int index ; public synchronized void push( Woto woto ) { while( wos.length == index ) { try { this.wait() ; } catch ( InterruptedException e ) { e.printStackTrace(); } } this.notify() ; wos[ index ] = woto ; ++ index ; System.out.println( Thread.currentThread().getName() + "_____________生产了馒头->>" + woto ) ; } public synchronized Woto pop() { while( 0 == index ) { try { this.wait() ; } catch ( InterruptedException e ) { e.printStackTrace(); } } this.notify() ; -- index ; System.out.println( Thread.currentThread().getName() + "%%%消费了馒头->>" + wos[index] ) ; return wos[ index ] ; } } /** * 窝头类 * */ class Woto { private String name ; public Woto( String name ) { this.name = name ; } public String toString() { return "[窝头:" + this.name + "]" ; } } /** * 生产者 * */ class Producer implements Runnable { private SyncStack wotos ; public Producer( SyncStack wotos ) { this.wotos = wotos ; } public void run() { for( int i = 0 ; i < 2000 ; i ++ ) { Woto woto = new Woto( String.valueOf( i ) ) ; this.wotos.push( woto ) ; // try // { // Thread.sleep( (int)(Math.random() * 2) ) ; // } // catch ( InterruptedException e ) // { // e.printStackTrace(); // } } } } /** * 消费者 * */ class Consumer implements Runnable { private SyncStack wotos ; public Consumer( SyncStack wotos ) { this.wotos = wotos ; } public void run() { for( int i = 0 ; i < 2000 ; i ++ ) { this.wotos.pop() ; try { Thread.sleep( (int)(Math.random() * 2 ) ) ; } catch ( InterruptedException e ) { e.printStackTrace(); } } } }
相关文章推荐
- java线程同步(生产者消费者应用-模拟叫号系统)
- java线程模拟生产者消费者问题
- JAVA学习笔记(1)_____模拟线程通信之生产者消费者问题
- java线程(2)——模拟生产者与消费者
- java 线程模拟生产者和消费者
- java 线程 生产者-消费者与队列,任务间使用管道进行输入、输出 讲解示例 --thinking java4
- java生产者消费者问题(线程同步与线程等待的应用)
- java线程生产者与消费者模型
- Java模拟生产者消费者问题
- Java线程:并发协作-生产者消费者模型
- Java线程:并发协作-生产者消费者模型
- java线程间通信:生产者--消费者
- java 线程-一对一生产者消费者
- java基础—线程间的通讯 生产者与消费者
- Java线程:并发协作-生产者消费者模型
- java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)
- java简单模拟生产者消费者问题
- Java线程----生产者消费者模型
- 学习和理解JAVA线程同步--生产者与消费者例子
- java线程:三种方式实现生产者消费者问题_2