且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用UncaughtExceptionHandler重启线程

更新时间:2022-05-28 07:48:46

使用UncaughtExceptionHandler重启线程

我们已经知道,Java中有两种异常,即已检测异常和未检测异常。已检测的异常必须在抛出语句(throws clause)的方法中指定或者捕获。未检测的异常不需要指定或捕获。因为run()方法不接受抛出语句,所以当一个检测的异常在一个Thread对象的 run()方法中抛出,我们需要对其进行捕获并做相应的处理。但是当一个未检测的异常在一个线程的run()方法中抛出,默认的行为是将堆栈跟踪信息写到 控制台中(或者记录到错误日志文件中)然后退出程序。

幸运的是,Java为我们提供了一个机制,用来捕获并处理在一个线程对象中抛出的未检测异常,以避免程序终止。我们可以通过UncaughtExceptionHandler来实现这种机制。

让我们来做个UncaughtExceptionHandler的使用 示例。在这个例子中,我们已经创建一个线程,这个线程尝试解析一些本来应该是整数的字符串。我们已经写出run()方法,让它在执行时抛出 java.lang.NumberFormatException。当程序不去捕获异常时,异常经过JVM的同时线程也被杀死。这确实属于正常的行为,但 不是我们希望看到的。

不使用UncaughtExceptionHandler

在现实生活的应用中,对于一个关键的任务,虽然已经失败了几次,但是你依然愿意尝试再执行几次。下面的例子解释了这个用例,首先不使用UncaughtExceptionHandler时,线程在执行失败之后立即终止。

Task.java

1
2
3
4
5
6
7
8
9
10
11
12
class Task implements Runnable
{
   @Override
   public void run()
   {
      System.out.println(Integer.parseInt("123"));
      System.out.println(Integer.parseInt("234"));
      System.out.println(Integer.parseInt("345"));
      System.out.println(Integer.parseInt("XYZ")); //This will cause NumberFormatException
      System.out.println(Integer.parseInt("456"));
   }
}

DemoThreadExample.java

1
2
3
4
5
6
7
8
9
public class DemoThreadExample
{
   public static void main(String[] args)
   {
      Task task = new Task();
      Thread thread = new Thread(task);
      thread.start();
   }
}

下面是线程运行时的输出:

1
2
3
4
5
6
7
8
9
123
234
345
Exception in thread "Thread-0" java.lang.NumberFormatException: For input string: "XYZ"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at examples.algorithms.sleepingbarber.Task.run(DemoThreadExample.java:24)
    at java.lang.Thread.run(Unknown Source)

使用UncaughtExceptionHandler之后

首先,我们实现UncaughtExceptionHandler接口,用来捕获运行时的任意未检测的异常。

ExceptionHandler.java

1
2
3
4
5
6
7
8
9
10
11
12
13
class ExceptionHandler implements UncaughtExceptionHandler
{
   public void uncaughtException(Thread t, Throwable e)
   {
      System.out.printf("An exception has been capturedn");
      System.out.printf("Thread: %sn", t.getId());
      System.out.printf("Exception: %s: %sn", e.getClass().getName(), e.getMessage());
      System.out.printf("Stack Trace: n");
      e.printStackTrace(System.out);
      System.out.printf("Thread status: %sn", t.getState());
      new Thread(new Task()).start();
   }
}

将异常处理程序添加到线程:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Task implements Runnable
{
   @Override
   public void run()
   {
      Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());
      System.out.println(Integer.parseInt("123"));
      System.out.println(Integer.parseInt("234"));
      System.out.println(Integer.parseInt("345"));
      System.out.println(Integer.parseInt("XYZ")); //This will cause NumberFormatException
      System.out.println(Integer.parseInt("456"));
   }
}

再次运行上面的例子,会发现线程能够持续执行。实际上,如果线程完成了任务,那么它在退出时不会抛出任何异常,从而完成自身生命周期。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
123
234
345
An exception has been captured
Thread: 1394
Exception: java.lang.NumberFormatException: For input string: "XYZ"
Stack Trace:
java.lang.NumberFormatException: For input string: "XYZ"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at examples.algorithms.sleepingbarber.Task.run(DemoThreadExample.java:24)
    at java.lang.Thread.run(Unknown Source)
Thread status: RUNNABLE
123
234
345
An exception has been captured
Thread: 1395
Exception: java.lang.NumberFormatException: For input string: "XYZ"
Stack Trace:
java.lang.NumberFormatException: For input string: "XYZ"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at examples.algorithms.sleepingbarber.Task.run(DemoThreadExample.java:24)
    at java.lang.Thread.run(Unknown Source)
Thread status: RUNNABLE
123
234
345

上面的程序实现帮你运行一个线程,在完成任务之前,这个线程会持续运行。通过其他多线程的思想同样可以实现这种情况。

请注意:UncaughtExceptionHandler可以在无需重启线程的条件下,将日志记录变得更加健壮,因为默认日志在线程执行失败时,不会提供足够的上下文信息。

学习愉快!

原文链接: howtodoinjava 翻译: ImportNew.com Angus
译文链接: http://www.importnew.com/14434.html