温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java通过线程如何解决生产者/消费者问题

发布时间:2020-10-28 19:04:58 来源:亿速云 阅读:143 作者:Leah 栏目:开发技术

Java通过线程如何解决生产者/消费者问题?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,如下图所示

Java通过线程如何解决生产者/消费者问题

生产者向空间里存放数据,而消费者取用数据,如果不加以协调可能会出现以下情况:

存储空间已满,而生产者占用着它,消费者等着生产者让出空间从而去除产品,生产者等着消费者消费产品,从而向空间中添加产品。互相等待,从而发生死锁。

以下实例演示了如何通过线程解决生产者/消费者问题:

/*
 author by javaidea.com
 ProducerConsumerTest.java
 */

public class ProducerConsumerTest {
  public static void main(String[] args) {
   CubbyHole c = new CubbyHole();
   Producer p1 = new Producer(c, 1);
   Consumer c1 = new Consumer(c, 1);
   p1.start(); 
   c1.start();
  }
}
class CubbyHole {
  private int contents;
  private boolean available = false;
  public synchronized int get() {
   while (available == false) {
     try {
      wait();
     }
     catch (InterruptedException e) {
     }
   }
   available = false;
   notifyAll();
   return contents;
  }
  public synchronized void put(int value) {
   while (available == true) {
     try {
      wait();
     }
     catch (InterruptedException e) { 
     } 
   }
   contents = value;
   available = true;
   notifyAll();
  }
}

class Consumer extends Thread {
  private CubbyHole cubbyhole;
  private int number;
  public Consumer(CubbyHole c, int number) {
   cubbyhole = c;
   this.number = number;
  }
  public void run() {
   int value = 0;
     for (int i = 0; i < 10; i++) {
      value = cubbyhole.get();
      System.out.println("消费者 #" + this.number+ " got: " + value);
     }
  }
}

class Producer extends Thread {
  private CubbyHole cubbyhole;
  private int number;

  public Producer(CubbyHole c, int number) {
   cubbyhole = c;
   this.number = number;
  }

  public void run() {
   for (int i = 0; i < 10; i++) {
     cubbyhole.put(i);
     System.out.println("生产者 #" + this.number + " put: " + i);
     try {
      sleep((int)(Math.random() * 100));
     } catch (InterruptedException e) { }
   }
  }
}

以上代码运行输出结果为:

消费者 #1 got: 0
生产者 #1 put: 0
生产者 #1 put: 1
消费者 #1 got: 1
生产者 #1 put: 2
消费者 #1 got: 2
生产者 #1 put: 3
消费者 #1 got: 3
生产者 #1 put: 4
消费者 #1 got: 4
生产者 #1 put: 5
消费者 #1 got: 5
生产者 #1 put: 6
消费者 #1 got: 6
生产者 #1 put: 7
消费者 #1 got: 7
生产者 #1 put: 8
消费者 #1 got: 8
生产者 #1 put: 9
消费者 #1 got: 9

看完上述内容,你们掌握Java通过线程如何解决生产者/消费者问题的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI