生产者消费者-java 3种

public class Util {
	public static final String produce = "生产者";
	public static final String consumer = "消费者";
	public static final int MAX = 10;
	public static void msg(String msg) {
		System.out.println(msg);
	}
}

根据代码块 建议通过抽象类  尝试着写下

第一种:

import java.util.LinkedList;
/**
 * 生产者消费者
 * 仓库
 * wait/notify
 * @author 15011
 */
public class Storage {
	private static final int MAX = 10;
	//仓库存储载体
	private LinkedList<Object> container = new LinkedList<>();
	class Producer extends Thread{
		@Override
		public void run() {
			try { add(); } catch (Exception e) { } 
		}
	}
	class Consumer extends Thread{
		@Override
		public void run() {
			try { cut(); } catch (Exception e) { }
		}
	}
	public void add() throws Exception {
		String produce = "生产者:";
		while(true) {
			synchronized (container) {
				while(container.size() >= MAX) {
					msg(produce+Thread.currentThread().getName()+"-->仓库已满");
					container.wait();
				}
				container.add(Math.random());
				msg(produce+Thread.currentThread().getName()+"-->生产1个,现库存:"+container.size());
				//通知等待池中的所有线程,仓库有货了
				container.notifyAll();
				//避免打印过快
				Thread.sleep(500);
			}
		}
	}
	public void cut() throws Exception {
		String consumer = "消费者:";
		while(true) {
			synchronized (container) {
				while(container.size() == 0) {
					msg(consumer+Thread.currentThread().getName()+"仓库为空");
					container.wait();
				}
				container.remove();
				msg(consumer+Thread.currentThread().getName()+"消费一个产品,现库存:"+container.size());
				container.notifyAll();
				Thread.sleep(500);
			}
		}
	}
	private static void msg(String msg) {
		System.out.println(msg);
	}
	public static void main(String[] args) {
		//notify,wait
		Storage storage = new Storage();
		Consumer consumer = storage.new Consumer();
		Producer producer = storage.new Producer();
		consumer.start();
		producer.start();
	}
}

第二种:

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
 * 生产者消费者
 * 仓库
 * await() / signal()
 * @author 15011
 */
public class StorageLock {
	//仓库存储载体
	private LinkedList<Object> container = new LinkedList<>();
	//建议了解FairSync,NonfairSync==> new ReentrantLock(true)
	private final Lock lock = new ReentrantLock();//互斥锁 提问:为什么使用final修饰
	//仓库满的锁
	private Condition in = lock.newCondition();//提问:为什么使用final修饰-代码中不写final了,但可以添加上去
	//仓库空的锁
	private Condition out = lock.newCondition();//提问:为什么使用final修饰
	class Producer extends Thread{
		@Override
		public void run() {
			add();
		}
	}
	class Consumer extends Thread{
		@Override
		public void run() {
			cut();
		}
	}
	public void add() {
		while(true){
			lock.lock();
			try {
				while(container.size()>=Util.MAX) {//提问:为什么不用if
					Util.msg(Util.produce+Thread.currentThread().getName()+"-->仓库已满");
					in.await();
				}
				container.add(Math.random());
				Util.msg(Util.produce+Thread.currentThread().getName()+"-->生产1个,现库存:"+container.size());
				//发出仓库有货信号,可以出库了
				out.signal();
				Thread.sleep(500);
			}catch (Exception e) {
			}finally {
				lock.unlock();
			}
		}
	}
	public void cut() {
		while(true) {
			lock.lock();
			try {
				while(container.isEmpty()) {//提问:等待条件判断为什么不用if
					Util.msg(Util.consumer+Thread.currentThread().getName()+"-->仓库为空");
					out.await();
				}
				container.remove();
				Util.msg(Util.consumer+Thread.currentThread().getName()+"-->出库1个,现库存:"+container.size());
				//发出库存有空位的信号,可以入库了
				in.signal();
				Thread.sleep(500);
			} catch (Exception e) {
			} finally {
				lock.unlock();
			}
		}
	}
	public static void main(String[] args) {
		//signal,await
		StorageLock storage = new StorageLock();
		Producer producer = storage.new Producer();
		Consumer consumer = storage.new Consumer();
		consumer.start();
		producer.start();
	}
	//提问1
	//[等待条件判断不用if 这个问题也不绝对]
	//可以将本例的中等待条件while改为if 不会出现问题
	//参考使用if出现问题的例子如下博客分析也可了解
	//答: https://blog.csdn.net/hqq_123/article/details/107777492
	
	//提问2
	//[为什么使用final修饰锁对象]
	//答: final修饰的对象必须被初始化,不能被修改。非final的对象可以被重新赋值,锁对象就不受管控了。当一个锁被其他对象占有时,当前线程可以对锁对象重新赋值(相当于从新创建了一个锁对象),从而也拿到了运行的权利。
	//对于final关键字的解答可以参考如下博客
	//https://blog.csdn.net/zqz_zqz/article/details/79438502
}

第三种:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
 * 生产者消费者
 * 仓库
 * BlockingQueue阻塞队列 建议了解BlockingQueue里面各对应的api
 * 底层使用的就是StorageLock中的lock方式 condition
 * @author 15011
 */
public class StorageBQ {
//	poll -->【若队列为空,返回null】
//	put  --> 【若队列已满,发生阻塞,等待减少元素】remove >【若队列为空,抛出NoSuchElementException异常】add与之对应
//	take -->【若队列为空,发生阻塞,等待有元素】	put
	private BlockingQueue<Object> container = new ArrayBlockingQueue<>(10);

	class Producer extends Thread{
		@Override
		public void run() {
			while(true) {
				try { add(); } catch (Exception e) { }
			}
		}
	}
	class Consumer extends Thread{
		@Override
		public void run() {
			while(true) {
				try { cut(); } catch (Exception e) { }
			}
		}
	}
	private void add() throws Exception {
		container.put(Math.random());
		Util.msg(Util.produce+Thread.currentThread().getName()+"-->入库1个,现库存:"+container.size());
	}
	private void cut() throws Exception {
		container.take();
		Util.msg(Util.consumer+Thread.currentThread().getName()+"-->出库1个,现库存:"+container.size());
	}
	public static void main(String[] args) {
		StorageBQ storage = new StorageBQ();
		Producer producer = storage.new Producer();
		Consumer consumer = storage.new Consumer();
		producer.start();
		consumer.start();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值