Raj*_*esh 0 java multithreading
public class Test {
public static void main(String args[]) throws Exception{
try{
System.out.print("1");
throw new Exception("first");
}
catch (Exception e) {
System.out.print("2");
throw new Exception("second");
}
**finally**{
System.out.print("3");
try{
System.out.print("4");
}catch (Exception e) {
System.out.print("5");
throw new Exception("third");
}
finally{
System.out.print("6 ");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
首次输出:
12Exception in thread "main" 346 java.lang.Exception: second
at src.dec.TST501.main(TST501.java:11)
Run Code Online (Sandbox Code Playgroud)
第二轮输出:
12346 Exception in thread "main" java.lang.Exception: second
at src.dec.TST501.main(TST501.java:11)
Run Code Online (Sandbox Code Playgroud)
第三次运行输出:1线程"main"中的异常java.lang.Exception:src.dec.TST501.main中的第二个2346(TST501.java:11)
任何人都可以解释一下它是如何发生的吗?finally块是否会在除main之外的任何其他线程中执行?
该finally块在同一个线程上执行.输出以这种方式交错的原因与标准输出和标准错误输出数据的方式有关.
标准输出是缓冲的(而标准错误不是),因此输出如何交错取决于系统何时选择刷新输出缓冲区.(由于您的终端仿真器只是将这两个流一起显示,您可以获得您观察到的混合输出.)
| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |