消费者与生产者问题是多线程中比较经典的问题之一,在学习并发编程中往往会针对这个问题来讲解程序的设计及思想,下面实现一个简单的单线程生产者与消费者模式。

public class Producer_Consumer {
	private int i = 0;
	
	Object LOCK = new Object();
	
	private boolean isProduce = false;
	
	public void  producer(){
		synchronized (LOCK) {
			if(isProduce){
				try {
					//生产过了,则等待
					LOCK.wait();
				} catch (InterruptedException e) {
					
					e.printStackTrace();
				}
			}else{
				i++;
				System.out.println("p:"+i);
				isProduce = true;
				//唤醒消费者
				LOCK.notify();
			}
		}
	}
	public void consumer(){
		synchronized (LOCK) {
			if(isProduce){
				System.out.println("c:"+i);
				isProduce = false;
				//消费完毕,唤醒生产者生产
				LOCK.notify();
			}else{
				try {
					//无数据消费,等待生产者生产
					LOCK.wait();
				} catch (InterruptedException e) {
					
					e.printStackTrace();
				}
			}
		}
	}
}

测试

public static void main(String[] args) {
		final Producer_Consumer pc = new Producer_Consumer();
		new Thread(){
			@Override
			public void run() {
				while(true){
					pc.producer();
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
				}
			}
		}.start();
		new Thread(){
			public void run() {
				while(true){
					pc.consumer();
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

运行结果

单线程模式的生产者消费者案例

相关文章: