加入线程时处理异常的最佳方法

Cra*_*lus 5 java concurrency multithreading exception

由于某种原因,我对以下内容感到困惑:
假设我Thread A绝对需要Thread B在完成处理后执行。
一种方法是Thread A加入Thread B.
简单的例子:

public class MainThread {  
    public static void main(String[] args){   
        Thread b = new Thread (new SomeRunnable(args[0]));  
        b.start();  
        try {   
            b.join();   
        } catch(InteruptedException e) {  
        }  
        // Go on with processing  
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题如下:在这种情况下处理异常的正确方法是什么?

在我见过的各种例子中,即使在教科书中,异常也被忽略。
因此,如果Thread A需要确保Thread B在继续之前完全完成,如果我由于异常而最终陷入困境,那么这种情况是否Thread B实际上仍然可以运行/正在运行?那么处理这个异常的最佳方法是什么?

Gra*_*ray 2

在这种情况下处理异常的正确方法是什么?

任何时候你得到一个InterruptedException当前线程都应该认为自己被中断了。通常,这意味着线程应该在自身之后进行清理并退出。在您的情况下,主线程被另一个线程中断,并且可能应该中断它Thread a依次启动的线程,然后退出。

尽管是否应该忽略中断取决于您,但我建议这是一个不好的做法。如果您使用中断作为线程的某种信号,那么我会设置一些volatile boolean标志。

就捕获时的最佳实践而言InterruptedException,我通常会这样做:

try {
    ...
} catch(InterruptedException e){  
    // a good practice to re-enable the interrupt flag on the thread
    Thread.currentThread().interrupt();
    // in your case you probably should interrupt the Thread a in turn
    a.interrupt();
    // quit the thread
    return;
}
Run Code Online (Sandbox Code Playgroud)

由于捕获会InterruptedException清除线程的中断标志,因此在 catch 块中重新启用中断标志始终是一个好主意。

在我见过的各种例子中,即使在教科书中,异常也被忽略。

的确。忽略任何异常是非常糟糕的做法,但这种情况经常发生。不要向黑暗势力屈服!

难道线程 B 实际上仍然可以运行/正在运行吗?

Thread B当然仍然可以运行。这是正在调用已被中断的主线程join()