gpt4 book ai didi

java - 中断等待阻塞操作的线程?

转载 作者:搜寻专家 更新时间:2023-10-31 08:06:00 25 4
gpt4 key购买 nike

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

我使用了 volatile boolean 值和 Interruption 的已知模式,但我不确定它是否有效:当我尝试为 InterruptedException 添加一个 catch block 时,我收到错误:

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

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

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

  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() 作为您的 while 条件。

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

最后,拦截方式是什么?是 scheduleSource() 吗?如果该方法没有抛出 InterruptedException,您将无法捕获它。

尝试以下操作:

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();
}

关于java - 中断等待阻塞操作的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1820118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com