码迷,mamicode.com
首页 > 其他好文 > 详细

Thread(生产者和消费者)

时间:2017-09-08 01:21:56      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:log   void   消费者   highlight   notify   trace   div   ring   push   

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(生产者和消费者)

标签:log   void   消费者   highlight   notify   trace   div   ring   push   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!