中断等待阻塞操作的线程? [英] Interrupting a thread that waits on a blocking action?

查看:293
本文介绍了中断等待阻塞操作的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个线程,其主要操作是使用阻塞函数调用代理,并等待它给它一些东西。

I am running a thread whose main action is to call on a proxy using a blocking function , and wait for it to give it something.

我使用了挥发性布尔值和中断的已知模式,但我不确定它是否可行:当我尝试为<添加一个catch块时code> InterruptedException ,我收到错误:

I've used the known pattern of a volatile boolean and the Interruption , but I'm not sure it will work: When I tried to add a catch block for InterruptedException , I get the error:


InterruptedException的无法访问的catch块。永远不会从try语句主体抛出此异常

Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body

因此,如果我永远不会得到 InterruptedException ,这意味着我永远不会摆脱阻止行动 - 因此永远不会停止。

So if I'm never going to get anInterruptedException, this means I'll never get out of the blocking action - thus will never stop.

我有点不解。有什么想法吗?

I'm a bit puzzled. Any idea?

  public void run() {    
    Proxy proxy = ProxyFactory.generateProxy();
    Source source;

    while (!isStopped) {
      try {
        source = proxy.getPendingSources();
        scheduleSource(source);
      } catch (Exception e) {
        log.error("UnExpected Exception caught while running",e);
      }
    }
  }

  public void stop() {
    this.isStopped = true;
    Thread.currentThread().interrupt();
  }


推荐答案

首先,你不要真的需要一个单独的标志(如果你这样做,使用 AtomicBoolean ),只需检查 Thread.currentThread()。isInterrupted()作为你的条件。

First, you don't really need a separate flag (if you do, use an AtomicBoolean), just check Thread.currentThread().isInterrupted() as your while condition.

其次,你的stop方法不起作用,因为它不会中断正确的线程。如果另一个线程调用stop,则代码使用 Thread.currentThread(),这意味着调用线程将被中断,而不是正在运行的线程。

Second, your stop method won't work because it won't interrupt the correct thread. If another thread calls stop, the code uses Thread.currentThread() which means the calling thread will be interrupted, not the running one.

最后,阻塞方法是什么?是 scheduleSource()?如果该方法没有抛出 InterruptedException ,你将无法捕获它。

Finally, what is the blocking method? Is it scheduleSource()? If that method doesn't throw InterruptedException, you won't be able to catch it.

请尝试以下方法:

private final AtomicReference<Thread> currentThread = new AtomicReference<Thread>();

public void run() {
    Proxy proxy = ProxyFactory.generateProxy();
    Source source;

    currentThread.set(Thread.currentThread());

    while (!Thread.currentThread().isInterrupted()) {
        try {
            source = proxy.getPendingSources();
            scheduleSource(source);
        } catch (Exception e) {
            log.error("UnExpected Exception caught while running", e);
        }
    }
}

public void stop() {
    currentThread.get().interrupt();
}

这篇关于中断等待阻塞操作的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆