生产者消费者模式

先生产后消费
实现方法一:使用lock锁机制实现

import java.util.concurrent.locks.Condition;
		import java.util.concurrent.locks.Lock;
		import java.util.concurrent.locks.ReentrantLock;
		
		class Data{
			volatile int number = 0;
			Lock lock = new  ReentrantLock();
			Condition condition = lock.newCondition();
			
			public void increment() throws InterruptedException{
				lock.lock();
				try {
					while(number != 0){
						condition.await();
					}
					number++;
					System.out.println(Thread.currentThread().getName()+" number = "+ number);
					condition.signalAll();
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					lock.unlock();
				}			
			}
			
			public void descrement(){
				lock.lock();
				try {
					while(number == 0){
						condition.await();
					}
					number--;
					System.out.println(Thread.currentThread().getName()+" number = "+ number);
					condition.signalAll();
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					lock.unlock();
				}	
			}
		}
		
		
		public class ProcudeConsumer {
			
			public static void main(String[] args) {
				Data data = new Data();
				 
				
					new Thread(()->{
						for (int i = 0; i < 5; i++) {
						try {
							data.increment();
						} catch (Exception e) {
							e.printStackTrace();
						}
						}
					},"AAAA").start();
				
					new Thread(()->{
						for (int i = 0; i < 5; i++) {
						data.descrement();
						}
					},"BB").start();
				
			}
			
		}

实现方法二:阻塞队列实现
使用阻塞队列,当队列中没有时无法消费,队列中满了时无法生产。

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyResource {
	private volatile boolean Flag = true;
	AtomicInteger atomicInteger = new AtomicInteger();
	BlockingQueue<String> blockingQueue = null;

	public MyResource(BlockingQueue<String> blockingQueue) {
		this.blockingQueue = blockingQueue;
		System.out.println(blockingQueue.getClass().getName());
	}

	public void doProduce() throws Exception {
		String data = null;
		boolean retValue;
		while (Flag) {
			data = atomicInteger.incrementAndGet() + "";
			retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
			if (retValue) {
				System.out.println(Thread.currentThread().getName() + "\t正在生产 "
						+ data);
			} else {
				System.out.println(Thread.currentThread().getName() + "\t 生产失败");
			}
			TimeUnit.SECONDS.sleep(1);
		}
		System.out.println("停止生产");
	}

	public void doConsumer() throws Exception {
		String poll;
		while (Flag) {
			poll = blockingQueue.poll(2, TimeUnit.SECONDS);
			atomicInteger.decrementAndGet();
			if (poll == null || poll.equals("")) {
				Flag = false;
				System.out.println("消费退出!!");
				System.out.println();
				System.out.println();
				System.out.println();
				return;
			}
			System.out.println(Thread.currentThread().getName() + "\t正在消费 "
					+ poll);
			TimeUnit.SECONDS.sleep(1);
		}

	}

	public void stop() {
		Flag = false;
	}

}

/**
 * 阻塞队列实现生产者消费者模式
 * 
 * @author yezhiming 2019年9月19日
 * @version
 */
public class BlockQueueProduceConsumer {
	public static void main(String[] args) {
		MyResource myResource = new MyResource(
				new ArrayBlockingQueue<String>(10));

		new Thread(() -> {
			try {
				System.out.println("生产线程启动!!!");
				myResource.doProduce();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}, "生产线程").start();

		new Thread(() -> {
			try {
				System.out.println("消费线程启动!!!");
				myResource.doConsumer();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}, "消费线程").start();

		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println();
		System.out.println();
		myResource.stop();
		System.out.println("结束!!");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值