代码:
package com.sdkd.hms;import javax.naming.Context;import java.util.ArrayList;import java.util.Stack;/** * Created by hms on 2017/2/15. */public class WakeOrSleep { public static final int N = 10; public static int count = 0; public static Stack<Integer> stack = new Stack(); public static void main(String[] args) { PRoducer producer = new Producer(); Consumer consumer = new Consumer(); producer.start(); consumer.start(); }}class Producer extends Thread{ @Override public void run() { while (true) { int item = (int)(Math.random() * 100); if(WakeOrSleep.count == WakeOrSleep.N) { System.out.println("缓冲区已经满了,等待消费者唤醒"); try { synchronized (WakeOrSleep.stack) { WakeOrSleep.stack.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } WakeOrSleep.stack.push(item); System.out.println("缓冲区添加了数据项 " + item); WakeOrSleep.count += 1; if(WakeOrSleep.count == 1){ synchronized (WakeOrSleep.stack) { WakeOrSleep.stack.notify(); } } } }}class Consumer extends Thread{ @Override public void run() { while (true) { if(WakeOrSleep.count == 0){ try { System.out.println("缓冲区已空,等待生产者唤醒"); synchronized (WakeOrSleep.stack) { WakeOrSleep.stack.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } int item = WakeOrSleep.stack.pop(); WakeOrSleep.count -= 1; if(WakeOrSleep.count == WakeOrSleep.N - 1) { synchronized (WakeOrSleep.stack) { WakeOrSleep.stack.notify(); } } System.out.println("缓冲区中消费了 " + item); } }}/**缓冲区已空,等待生产者唤醒缓冲区添加了数据项 45缓冲区中消费了 45缓冲区已空,等待生产者唤醒缓冲区添加了数据项 47缓冲区中消费了 47缓冲区已空,等待生产者唤醒缓冲区添加了数据项 84缓冲区添加了数据项 59缓冲区添加了数据项 81...*/新闻热点
疑难解答