基本上,就是问题标题所说的内容。
Thread t = new Thread(someRunnable);
t.start();
t.interrupt();
t.join(); //does an InterruptedException get thrown immediately here?
从我自己的测试来看,似乎是这样,但只是想确定一下。我猜 Thread.join()
在执行其“等待”例程之前检查线程的 interrupted
状态?
最佳答案
Does calling Thread.interrupt() before a Thread.join() cause the join() to throw an InterruptedException immediately?
不,它不会抛出。仅当调用 join()
方法的当前 线程被中断时,join()
才会抛出 InterruptedException
。 t.interrupt()
正在中断您刚刚启动的线程,而 t.join()
只会抛出 InterruptedException
如果正在执行的线程连接(也许是主线程?)本身被中断了。
Thread t = new Thread(someRunnable);
t.start();
t.interrupt();
t.join(); // will _not_ throw unless this thread calling join gets interrupted
同样重要的是要意识到中断一个线程并不会取消它并且 join()
不像Future
因为它将返回线程抛出的异常。
当您中断线程时,线程正在对 sleep()
、wait()
、join()
和其他可中断方法将抛出 InterruptedException
。如果未调用这些方法,则线程将继续运行。如果线程确实抛出一个InterruptedException
以响应被中断然后退出,除非您使用t.setDefaultUncaughtExceptionHandler(handler)
.
在您的情况下,如果线程因返回而中断并完成,则连接将完成——它不会抛出异常。正确处理中断的常用线程代码如下:
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// a good pattern is to re-interrupt the thread when you catch
Thread.currentThread().interrupt();
// another good pattern is to make sure that if you _are_ interrupted,
// that you stop the thread
return;
}
}
关于java - 在 Thread.join() 之前调用 Thread.interrupt() 会导致 join() 立即抛出 InterruptedException 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10632451/