码迷,mamicode.com
首页 > 编程语言 > 详细

生产者消费者线程同步

时间:2016-08-01 21:02:19      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

生产者与消费者模式简单介绍:

  生产者线程生产物品,然后将物品放置在一个空缓冲区中供消费者线程消费。消费者线程从缓冲区中获得物品,然后释放缓冲区。当生产者线程生产物品时,如果没有空缓冲区可用,那么生产者线程必须等待消费者线程释放出一个空缓冲区。当消费者线程消费物品时,如果没有满的缓冲区,那么消费者线程将被阻塞,直到新

public class ProduceConsumer {
	
	public static void main(String[] args) {
		SyncStack ss = new SyncStack();
		Producer pro = new Producer(ss);
		Consumer con = new Consumer(ss);
		new Thread(pro).start();
		new Thread(con).start();
	}

}
class Product{
	int id;
	public Product(int id){
		this.id = id;
	}
	public String toString(){
		return "Product:"+id;
	}
}

class SyncStack{
	int index = 0;
	Product[] arrPro = new Product[6];
	public synchronized void push(Product p){
		while(index == arrPro.length){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		this.notify();
		arrPro[index] = p;
		index++;
	}
	public synchronized Product pop(){
		while(index == 0){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		index--;
		return arrPro[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++){
			Product p = new Product(i);
			ss.push(p);
			System.out.println("生产了:"+p);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}


class Consumer implements Runnable{
	SyncStack ss = null;
	public Consumer(SyncStack ss){
		this.ss = ss;
	}
	public void run(){
		for(int i=0; i<20; i++){
			Product p = ss.pop();
			System.out.println("消费了:"+p);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

  

的物品被生产出来

生产者消费者线程同步

标签:

原文地址:http://www.cnblogs.com/hlongch/p/5727192.html

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