`
kankan1218
  • 浏览: 271905 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

生产者消费者问题

阅读更多

 1) 只要缓冲区有存储单元,生产者都可往其中存放信息;当缓冲区已满时, 
若任意生产者提出写要求,则都必须等待; 

 2) 只要缓冲区中有消息可取,消费者都可从缓冲区中取出消息;当缓冲区为 
空时,若任意消费者想取出信息,则必须等待; 

 3) 生产者们和消费者们不能同时读、写缓冲区。 

 

 

package edison.thread;

public class ProducerAndConsumer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		WotouStack ws = new WotouStack();
		Producer2 p = new Producer2(ws);
		Consumer2 c = new Consumer2(ws);
		new Thread(p).start();
		new Thread(p).start();
		new Thread(c).start();	
		new Thread(c).start();	
	}

}

class Wotou2 {
	private int id;

	public Wotou2(int id) {
		super();
		this.id = id;
	}

	public int getId() {
		return id;
	}

	public String toString() {
		return String.valueOf(getId());
	}

}

class WotouStack {
	Wotou2[] elements = new Wotou2[6];
	int top = 0;

	public synchronized Wotou2 pop() {
		System.out.println("消费前的窝头总个数:" + top);
		while (top == 0) { // 如果这里用if,万一中间被打断,程序就会继续往下执行,而不去检查到底是否还有Wotou了
			try {
				this.wait();// wait的意思是指当前线程进入等待状态,同时会放弃所持有的对象的锁。
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();// 唤醒在此对象监视器上处于等待状态的所有线程,使其重新获得监控器进入同步运行状态。
		top--;
		return elements[top];
	}

	public synchronized void push(Wotou2 w) {
		System.out.println("生产前的窝头总个数:" + top);
		while (top == elements.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		elements[top] = w;
		top++;
	}
}

class Producer2 implements Runnable {
	WotouStack ws;

	public Producer2(WotouStack ws) {
		this.ws = ws;
	}

	public void run() {
		for (int i = 0; i < 20; i++) {
			Wotou2 wotou = new Wotou2(i);
			ws.push(wotou);
			System.out.println("生产了: " + wotou);
			try {
				Thread.sleep((int)( Math.random() * 2000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

class Consumer2 implements Runnable {
	WotouStack ws;

	public Consumer2(WotouStack ws) {
		this.ws = ws;
	}

	public void run() {
		for (int i = 0; i < 20; i++) {
			Wotou2 wotou = ws.pop();
			System.out.println("消费了: " + wotou);
			try {
				Thread.sleep((int)( Math.random() * 4000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics