publicstaticvoidtestPrint(){ for (int i = 0; i < 5; i++) { System.out.println("now " + i); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } }
publicstaticvoidmain(String[] args){ try (Cost c = new Cost()) { testPrint(); } System.out.println("------over-------"); }
执行后输出如下:
1 2 3 4 5 6 7
now 0 now 1 now 2 now 3 now 4 cost: 55 ------over-------
如果代码块抛异常,也会正常输出耗时么?
1 2 3 4 5 6 7 8 9 10 11 12 13
publicstaticvoidtestPrint(){ for (int i = 0; i < 5; i++) { System.out.println("now " + i); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } if (i == 3) { thrownew RuntimeException("some exception!"); } } }
再次输出如下,并没有问题
1 2 3 4 5 6 7 8
now 0 now 1 now 2 now 3 cost: 46 Exception in thread "main" java.lang.RuntimeException: some exception! at com.git.hui.boot.order.Application.testPrint(Application.java:43) at com.git.hui.boot.order.Application.main(Application.java:50)