Xåp*_* - 13 java concurrency multithreading interrupt interrupted-exception
基本上,问题标题是什么.
Thread t = new Thread(someRunnable);
t.start();
t.interrupt();
t.join(); //does an InterruptedException get thrown immediately here?
Run Code Online (Sandbox Code Playgroud)
从我自己的测试来看,似乎,但只是想确定.我猜测在执行"等待"例程之前Thread.join()
检查interrupted
线程的状态?
Pet*_*rey 16
interrupt()
中断您中断的线程,而不是中断线程.
比照
Thread.currentThread().interrupt();
t.join(); // will throw InterruptedException
Run Code Online (Sandbox Code Playgroud)
Gra*_*ray 16
在Thread.join()之前调用Thread.interrupt()会导致join()立即抛出InterruptedException吗?
不,它不会扔.只有当调用方法的当前线程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
Run Code Online (Sandbox Code Playgroud)
此外,重要的是要意识到中断线程并不会取消它, 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;
}
}
Run Code Online (Sandbox Code Playgroud)