public class Test { public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
System.out.println("111111111");
e.printStackTrace();
System.out.println("999999999");
} }}在eclipse3.2中多次执行,发现有多种顺序,以调试方式执行,却只有一种结果!求解,谢谢!!
其中一种:java.lang.Exception
at com.majin.Test.main(Test.java:10)
111111111
999999999
try {
throw new Exception();
} catch (Exception e) {
System.out.println("111111111");
e.printStackTrace();
System.out.println("999999999");
} }}在eclipse3.2中多次执行,发现有多种顺序,以调试方式执行,却只有一种结果!求解,谢谢!!
其中一种:java.lang.Exception
at com.majin.Test.main(Test.java:10)
111111111
999999999
不过在黑窗口下就一种顺序
111111111
java.lang.Exception
at Test.main(Test.java:5)
999999999
e.printStackTrace();调用了System.err
所以不是程序的问题,是eclipse的console问题
try {
throw new Exception();
} catch (Exception e) {
synchronized (System.err) {
System.out.println("111111111");
}
synchronized (System.out) {
e.printStackTrace();
}
synchronized (System.err) {
System.out.println("999999999");
}
} }}
Exception e
System.out.println
是两个不同的对象执行顺序是由对象在进程时间片问题
下面方法可以试试
public class Test1 {
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
Thread.sleep(100);
System.out.println("111111111");
} catch (InterruptedException e1) {
e1.printStackTrace();
}
e.printStackTrace();
try {
Thread.sleep(100);
System.out.println("999999999");
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
private String name; public ThreadTest(String name){
this.name=name;
} public void run(){
forTest();
}
private void forTest(){
for(int i=0;i<1000;i++){
System.out.println(name+i);
}
}
public static void main(String[] args) {
new ThreadTest("a:").start();
new ThreadTest("b:").start();
new ThreadTest("c:").start();
}
}多跑几次,你就会发现,每次执行的输出顺序也是不同的。即使你加上同步,输出顺序同样在变化。你们对于线程了解的很浅呀,加强学习吧,同学们。