且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-10 21:21:02

首先,你不要真的需要一个单独的标志(如果你这样做,使用 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();
}