使用该
finally块中未捕获的异常将其杀死,或者将整个JVM杀死(这将杀死线程)。
finally除了不良的设计外,没有充分的理由停止执行块。如果不应该每次都运行它,则不要将其放在一个
finally块中。
使用下面的测试代码,我运行了两种不同的情况,以了解杀死时会发生什么
Thread:
- 启动
Thread
和sleep
主线程2秒钟。在内Thread
,几乎立即进入该finally
块,然后睡眠5秒钟。一旦主线程完成等待,终止Thread
使用stop
。 - 启动
Thread
并睡眠2秒钟。内Thread
,睡眠5秒进入前finally
块,然后睡一些内finally
给它被杀死的机会。
在第一种情况下,结果是该
finally块停止执行。在第二种情况下,其结果是,该
finally块完全执行,并且在
Thread这是
stopPED不会少。
输出(注意为所有输出添加的当前线程的名称):
thread-starting [main]trying [Thread-0]catching [Thread-0]finally-sleeping [Thread-0]thread-stopped [main] [main]thread-starting [main]trying-sleeping [Thread-1]thread-stopped [main]finally-sleeping [Thread-1]finally-done [Thread-1]
码:
public class Main{ public static void main(String[] args) { testThread(new TestRunnable()); println(""); testThread(new TestRunnable2()); } private static void testThread(Runnable runnable) { Thread testFinally = new Thread(runnable); println("thread-starting"); testFinally.start(); try { Thread.sleep(2000); } catch (InterruptedException e) { println("main-interrupted..."); } testFinally.stop(); println("thread-stopped"); } private static class TestRunnable implements Runnable { @Override public void run() { try { println("trying"); throw new IllegalStateException("catching"); } catch (RuntimeException e) { println(e.getMessage()); } finally { println("finally-sleeping"); try { Thread.sleep(5000); } catch (InterruptedException e) { println("finally-interrupted"); } println("finally-done"); } } } private static class TestRunnable2 implements Runnable { @Override public void run() { try { println("trying-sleeping"); Thread.sleep(5000); } catch (InterruptedException e) { println("trying-interrupted"); } finally { println("finally-sleeping"); try { Thread.sleep(5000); } catch (InterruptedException e) { println("finally-interrupted"); } println("finally-done"); } } } private static void println(String line) { System.out.printf("%s [%s]%n", line, Thread.currentThread().getName()); System.out.flush(); }}


