我正在测试一个简单的无限递归应用程序,但是我不明白为什么输出有重复的语句而没有换行。仅当我在新线程中的catch块中运行代码时,它才能正常工作。
public class Main{
private static long count = 0;
public static void main (String args[]){
new Main().start();
}
public void start(){
loop();
}
public void loop(){
try{
loop();
}catch (StackOverflowError e){
System.out.println("thread ended (id:" + Thread.currentThread().getId() + ") [count: " +count+"]");
++count;
start();
}
}
}
输出:
...
thread ended (id:1) [count: 214]thread ended (id:1) [count: 214]thread ended (id:1) [count: 214]thread ended (id:1) [count: 214]thread ended (id:1) [count: 214]
thread ended (id:1) [count: 215]thread ended (id:1) [count: 215]thread ended (id:1) [count: 215]thread ended (id:1) [count: 215]thread ended (id:1) [count: 215]
thread ended (id:1) [count: 216]thread ended (id:1) [count: 216]thread ended (id:1) [count: 216]thread ended (id:1) [count: 216]thread ended (id:1) [count: 216]
...
重复次数有时会有所不同(每行1条语句)
答案 0 :(得分:1)
将try / catch移至start
。
public class SO {
private static long count = 0;
public static void main(String args[]) {
new SO().start();
}
public void start() {
try {
loop();
} catch (StackOverflowError e) {
System.out.println("thread ended (id:" + Thread.currentThread().getId() + ") [count: " + count + "]");
++count;
start();
}
}
public void loop() {
loop();
}
}
从一个没有展开的调用堆栈的深处调用start
是一个坏主意。
输出:
thread ended (id:1) [count: 0]
thread ended (id:1) [count: 1]
thread ended (id:1) [count: 2]
thread ended (id:1) [count: 3]
thread ended (id:1) [count: 4]
thread ended (id:1) [count: 5]
thread ended (id:1) [count: 6]
thread ended (id:1) [count: 7]
thread ended (id:1) [count: 8]
thread ended (id:1) [count: 9]
thread ended (id:1) [count: 10]