Java并发-UncaughtExceptionHandler捕获线程异常并重新启动线程

一、

 1 public class Testun {
 2 
 3     public static  void main(String[] args) throws InterruptedException {
 4 
 5         Thread thread=new TaskThread(1);
 6         thread.setName("数据同步线程");
 7         thread.start();
 8 
 9     }
10 
11 
12 }
13 class TaskThread extends  Thread {
14     private int taskNum;
15 
16     public TaskThread(int num) {
17         this.taskNum = num;
18     }
19     @Override
20     public void run() {
21         //调用捕获异常,一定要放在要做逻辑的上面
22         Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
23         //todo
24 
25         int i=1/0;
26 
27     }
28 }
29 
30 class MyExceptionHandler implements UncaughtExceptionHandler {
31     @Override
32     public void uncaughtException(Thread t, Throwable e) {
33         //1.打印报错日志
34         System.out.println("zzl异常信息: " + e.getMessage());
35 
36         //2.重新启动线程
37         Thread[] threads = findAllThread(); //获取所有线程
38         for (Thread thread :threads){
39             if (thread.getName().trim().equalsIgnoreCase("数据同步线程")){//校验线程是否正在运行
40                 Thread thread1=new TaskThread(1);
41                 thread1.setName("数据同步线程");
42                 thread1.start();//重新启动线程
43             }
44         }
45     }
46 
47     public Thread[] findAllThread(){
48         ThreadGroup currentGroup =Thread.currentThread().getThreadGroup();
49 
50         while (currentGroup.getParent()!=null){
51             // 返回此线程组的父线程组
52             currentGroup=currentGroup.getParent();
53         }
54         //此线程组中活动线程的估计数
55         int noThreads = currentGroup.activeCount();
56 
57         Thread[] lstThreads = new Thread[noThreads];
58         //把对此线程组中的所有活动子组的引用复制到指定数组中。
59         currentGroup.enumerate(lstThreads);
60 
61         for (Thread thread : lstThreads) {
62             System.out.println("线程数量:"+noThreads+" 线程id:" + thread.getId() + " 线程名称:" + thread.getName() + " 线程状态:" + thread.getState());
63         }
64         return lstThreads;
65     }
66 }

猜你喜欢

转载自www.cnblogs.com/java-zzl/p/9568073.html