Thread(生产者和消费者)
2017-09-08 00:28
204 查看
package com.gdut.lang.thread; public class ProducerAndConsumer { public static void main(String[] args) { SyncStack ss = new SyncStack(); Producer p = new Producer(ss); Consumer c = new Consumer(ss); new Thread(p).start(); new Thread(c).start(); } } class WoTou { private int id; public WoTou(int id) { this.id = id; } public String toString() { return "WoTou : " + id; } } class SyncStack { int index = 0; WoTou[] arrWT = new WoTou[5]; public synchronized void push(WoTou wt) { if ( index == arrWT.length ) { //窝头数组满了 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } arrWT[index] = wt; index++; this.notify(); } public synchronized WoTou pop() { if ( index == 0 ) { //数组里面没窝头了 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } index--; this.notify(); return arrWT[index]; } } class Producer implements Runnable { SyncStack ss = null; public Producer(SyncStack ss) { this.ss = ss; } public void run() { for (int i = 0; i < 20; i++) { WoTou wt = new WoTou(i); ss.push(wt); System.out.println("Producer: " + wt); try { Thread.sleep((int)Math.random()*1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer implements Runnable { SyncStack ss = null; public Consumer(SyncStack ss) { this.ss = ss; } @Override public void run() { for ( int i = 0; i < 20; i++ ) { WoTou wt = ss.pop(); System.out.println("Consumer: " + wt); try { Thread.sleep((int)Math.random()*1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
相关文章推荐
- Thread中的生产者消费者
- 黑马程序员 java基础Thread生产者消费者
- java--thread 生产者消费者问题
- 在python中实现生产者和消费者的例子(四):使用thread模块和全局变量
- 黑马程序员 java基础Thread生产者消费者
- Java中Thread的使用、死锁以及生产者消费者问题详解
- Java中Thread的使用、死锁以及生产者消费者问题详解
- Thread--不同步的生产者与消费者
- java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)
- Thread--不同步的生产者与消费者
- Thread详解9:用wait/notify实现生产者/消费者模式
- [Java] Thread-05- 线程同步-生产者与消费者的经典问题
- 多线程 生产者&消费者 哲学家进餐 & random & synchronized & Thread & Sleep
- [Java] Thread-05- 线程同步-生产者与消费者的经典问题
- C# Thread 多线程 Monitor 锁 Producer And Consumer 生产者和消费者 经典模型
- Thread生产者消费者例子
- java基础知识回顾之java Thread类学习(八)--java多线程通信等待唤醒机制经典应用(生产者消费者)
- 黑马程序员-Thread-生产者消费者
- C++ std::thread 简单的生产者和消费者
- Thread的生产者和消费者模式