生产者消费者线程同步

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

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

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();
			}
		}
	}
}

  

的物品被生产出来

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