消费者在使用ExecutorService.submit时没有退出

时间:2016-08-18 00:26:37

标签: java executorservice

我正在尝试使用ExecutorService在Java中实现一个小的生产者 - 消费者示例。

这是我的主要课程

public class Producer implements Runnable {
  private BlockingQueue<String> queue;
  public Producer(BlockingQueue<String> queue) {
    this.queue = queue;
  }

  @Override
  public void run() {
    for (int i = 0; i < 10; i++) {
      try {
        queue.put(i + "HELPPPPP");
      } catch (InterruptedException ex) {
        Logger.getLogger(MigrationToolProducer.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

制作人类

public class Consumer implements Runnable {
  private final BlockingQueue<String> queue;
    private volatile boolean keepRunning = true;

  public Consumer(BlockingQueue<String> queue) {
    this.queue = queue;
  }

  @Override
  public void run() {
     while (keepRunning) {
      String value;
      try {
        value = queue.take();
      } catch(InterruptedException e) {
        throw new RuntimeException(e);
      }
       System.out.println(value);
    }
  }
}

消费者类

The execution is stuck at queue.take() in Consumer Class.

编辑 String capchavalue = driver.findElement(By.xpath("")).getText(); int firstinteger= Integer.parseInt(capchavalue.substring(0, 2)); int secondinteger= Integer.parseInt(capchavalue.substring(5, 6)); int calc= firstinteger+secondinteger; String final_value= String.valueOf(calc); driver.findElement(By.xpath("")).sendKeys(final_value); 有人可以帮我解决这个问题吗?为什么执行卡在消费者身上?

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案:

1)在制作人一侧,在原来的10次放置后放置一个“END”信号:

queue.put("END");

2)在消费者方面,一旦检测到“END”信号,就打破循环:

public void run() {
while (keepRunning) {
  String value;
  try {
    value = queue.take();
    if(value.equals("END")) {
       System.out.println("Get END signal. All done!");
       break;
    }
  } catch(InterruptedException e) {
    throw new RuntimeException(e);
  }
  System.out.println(value);
}

}