谢谢 ChDw(米) ,问个额外相关问题:class MultiThread { public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); int index = 0; while (true) { if (index == 1000) { break; } index++; System.out.println("main:" + Thread.currentThread().getName()); } } }class MyThread extends Thread { public void run() { while (true) { System.out.println(Thread.currentThread().getName()); throw new IndexOutOfBoundsException(); //这句放这 } //throw new IndexOutOfBoundsException(); 为什么不能放在 while 语句的外面 } }
while (true) { System.out.println(Thread.currentThread().getName()); throw new IndexOutOfBoundsException(); //这句放这 } //throw new IndexOutOfBoundsException(); 因为这句话永远不可能到达,编译器已经做过这样的判断了如果while循环中没有再现异常则继续循环,出现异常就已经退出这个函数,所以它不可能到达
mt.setDaemon(true);这里会抛出IllegalThreadStateException异常啊
因为你打印太快没有注意罢了
MyThread不受任何的影响,还在执行中,所以JVM还不能退出
MyThread mt=new MyThread(); mt.start();
mt.setDaemon(true); 出现异常的语句是 mt.setDaemon(true); 是 mt对象,是MyThread 线程的对象,应该要是 MyThread 线程出异常才对,为什么是 main 线程?
public static void main(String[] args) {
MyThread mt = new MyThread(); mt.start();
int index = 0;
while (true) {
if (index == 1000) {
break;
}
index++;
System.out.println("main:" + Thread.currentThread().getName());
}
}
}class MyThread
extends Thread {
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
throw new IndexOutOfBoundsException(); //这句放这
}
//throw new IndexOutOfBoundsException(); 为什么不能放在 while 语句的外面
}
}
System.out.println(Thread.currentThread().getName());
throw new IndexOutOfBoundsException(); //这句放这
}
//throw new IndexOutOfBoundsException(); 因为这句话永远不可能到达,编译器已经做过这样的判断了如果while循环中没有再现异常则继续循环,出现异常就已经退出这个函数,所以它不可能到达