相关疑难解决方法(0)

如何中断在take()上阻塞的BlockingQueue?

我有一个从a获取对象的类,BlockingQueue并通过take()在连续循环中调用来处理它们.在某些时候,我知道不会有更多的对象被添加到队列中.如何中断该take()方法以阻止其阻塞?

这是处理对象的类:

public class MyObjHandler implements Runnable {

  private final BlockingQueue<MyObj> queue;

  public class MyObjHandler(BlockingQueue queue) {
    this.queue = queue;
  }

  public void run() {
    try {
      while (true) {
        MyObj obj = queue.take();
        // process obj here
        // ...
      }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是使用此类处理对象的方法:

public void testHandler() {

  BlockingQueue<MyObj> queue = new ArrayBlockingQueue<MyObj>(100);  

  MyObjectHandler  handler = new MyObjectHandler(queue);
  new Thread(handler).start();

  // get objects for handler to process …
Run Code Online (Sandbox Code Playgroud)

java concurrency interrupt blocking

81
推荐指数
3
解决办法
4万
查看次数

标签 统计

blocking ×1

concurrency ×1

interrupt ×1

java ×1