首页 > 其他 > 详细

Thread(生产者和消费者)

时间:2017-09-08 00:55:19      阅读:324      评论:0      收藏:0      [点我收藏+]
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(生产者和消费者)

原文:http://www.cnblogs.com/myseries/p/7492631.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!