1.Thread程序终止有两种方式a.)run方法执行结束 b).run中抛出异常,该异常会被Thread的ThreadGroup层顺流向上传 送,到达ThreadGroup root,尤其进行处理
2.通过UncaughtExceptionHandler来完成ThreadGroup异常处理的工作
public class BubbleSortThread extends Thread {
private int[] numbers;
public BubbleSortThread(int[] numbers) {
setUncaughtExceptionHandler(new SimpleThreadExceptionHandler());
this.numbers = numbers;
}
@Override
public void run() {
int index = numbers.length;
boolean finished = false;
while(!finished){
index--;
finished = true;
for(int i=0;i<index;i++){
if(numbers[i] < 0)throw new RuntimeException("不能为负数!");
if(numbers[i] > numbers[i+1]){
int temp = numbers[i];
numbers[i] = numbers[i+1];
numbers[i+1] = temp;
}
finished = false;
}
}
System.out.println("run finished.....");
}
private static void printArray(int[] numbers){
for(int temp : numbers){
System.out.print(temp+",");
}
System.out.println();
}
public static void main(String[] args) {
int[] numbers = new int[]{3,1,4,7,23,3,45,23};
Thread t = new BubbleSortThread(numbers);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
printArray(numbers);
int[] numbers2 = new int[]{-3,-1,-4,-7,-23,-3,-45,-23};
Thread t2 = new BubbleSortThread(numbers2);
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
printArray(numbers2);
}
}
class SimpleThreadExceptionHandler implements Thread.UncaughtExceptionHandler{
public void uncaughtException(Thread t, Throwable e) {
System.out.println(".....");
System.out.println("theandName:"+t.getName()+e.getMessage()+e.getStackTrace()[0].getLineNumber()+e.getStackTrace()[0].getFileName());
}
}
setUncaughtExceptionHandler(new SimpleThreadExceptionHandler());
设定Thread的UncaughtExceptionHandler,此Thread的throw异常,都会被
SimpleThreadExceptionHandler自动处理