在Thread.join()之前调用Thread.interrupt()会导致join()立即抛出InterruptedException吗?

基本上,问题标题是什么。

Thread t = new Thread(someRunnable); t.start(); t.interrupt(); t.join(); //does an InterruptedException get thrown immediately here? 

从我自己的测试来看,似乎,但只是想确定。 我猜测Thread.join()在执行“等待”例程之前检查线程的interrupted状态?

interrupt()中断你中断的线程,而不是中断线程。

比照

 Thread.currentThread().interrupt(); t.join(); // will throw InterruptedException 

在Thread.join()之前调用Thread.interrupt()会导致join()立即抛出InterruptedException吗?

不,它不会扔。 只有当调用join()方法的当前线程被中断时, join()才会抛出InterruptedExceptiont.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 ,因为它将返回线程抛出的exception。

当你中断一个线程时,线程进入sleep()wait()join()和其他可中断方法的任何调用都将抛出InterruptedException 。 如果未调用这些方法,则线程将继续运行。 如果一个线程确实抛出了InterruptedException以响应被中断然后退出,那么除非你使用了t.setDefaultUncaughtExceptionHandler(handler)否则该exception将会丢失。

在你的情况下,如果线程被中断并因为它返回而结束,那么连接将完成 – 它不会抛出exception。 正确处理中断的通用线程代码如下:

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