生产/消费模型的java实现

        生产者消费者模型,其实就是一个(生产者)负责产生数据,另一个(消费者)负责使用数据,这里的数据就是生产者和消费者共用的资源,为了让生产者和消费者能有序地使用公共资源,需要引入锁(synchronized)的概念----在一段代码中,将那一段需要很多线程共同使用的代码(相当于共享资源)用synchronized关键字定义,相当于给这一段区域进行了加锁,当有线程来操作它时,就会对其加锁,其他的线程在此时若准备操作它只能排队等待,等第一个线程操作完成,锁解除之后,才能操作。

下面实现的生产消费模型主要是:

1.仓库中无产品时,生产者开始生产一件放入仓库,通知消费者来取;

2.消费者从仓库中取出产品后,仓库没有库存,通知生产者去继续生产。

3.生产者和消费者是两个互不干扰的线程,但是又有一定的联系,联系就是通过仓库这个被锁定的区域实现的。

4.wait()和notify()方法就是生产者和消费者线程之间的联系,当一方在使用公共资源时,另一方的状态为wait,当这一方使用公共资源完毕后,会notify(通知)等待的一方。

生产者代码:

Java代码 复制代码 收藏代码
  1. package Producer_customer0123;
  2. import java.util.List;
  3. public class ProducerThread extends Thread {
  4. private List<Things> thingslist;//产品队列
  5. int count=0;
  6. public ProducerThread(List<Things> thingslist){
  7. this.thingslist=thingslist;
  8. }
  9. public void run(){
  10. while(true){
  11. //休眠2秒
  12. try {
  13. Thread.sleep(2000);
  14. } catch (InterruptedException e1) {
  15. e1.printStackTrace();
  16. }
  17. synchronized (thingslist) {
  18. while(thingslist.size()>0){//如果有产品,则等待
  19. try {
  20. thingslist.wait();
  21. System.out.println("生产者在等待-------生产者线程");
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. while(thingslist.size()==0){//如果没有产品,则生产产品,并且通知消费者
  27. Things newthing=new Things();
  28. count++;
  29. newthing.id=count;
  30. newthing.name="第"+count+"个产品";
  31. thingslist.add(newthing);//加入到队列中
  32. thingslist.notify();//通知消费者
  33. System.out.println("生产者生产了"+count+"号产品-------生产者线程");
  34. }
  35. }
  36. }
  37. }
  38. }  
原文地址:https://www.cnblogs.com/bjanzhuo/p/3576051.html