标签:
这一章节我们来讨论一下多线程的异常捕捉。
1.普通情况的异常
package com.ray.ch17; public class Test { public static void main(String[] args) { try { new ThreadA().run(); } catch (Exception e) { System.out.println("捕捉到异常"); } } } class ThreadA implements Runnable { @Override public void run() { throw new RuntimeException(); } }
捕捉到异常
2.多线程的异常
package com.ray.ch17; public class Test { public static void main(String[] args) { try { new Thread(new ThreadA()).start(); } catch (Exception e) { System.out.println("捕捉到异常"); } } } class ThreadA implements Runnable { @Override public void run() { throw new RuntimeException(); } }
Exception in thread "Thread-0" java.lang.RuntimeException
at com.ray.ch17.ThreadA.run(Test.java:18)
at java.lang.Thread.run(Thread.java:662)
3.问题:
在普通的情况下,我们可以顺利的捕捉到异常,但是如果在多线程的情况下,捕捉异常的方式其实不是上面的那种
4.解决方案
实现Thread.UncaughtExceptionHandler接口
(1)使用普通的方式来实现
package com.ray.ch17; public class Test { public static void main(String[] args) { try { Thread thread = new Thread(new ThreadA()); thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler()); thread.start(); } catch (Exception e) { System.out.println("捕捉到异常"); } } } class ThreadA implements Runnable { @Override public void run() { throw new RuntimeException(); } } class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("捕捉到:" + t.getName() + "的异常"); } }
捕捉到:Thread-0的异常
(2)使用线程池的方式来实现
package com.ray.ch17; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; public class Test { public static void main(String[] args) { ExecutorService executorService = Executors .newCachedThreadPool(new MyThreadFactory()); executorService.execute(new ThreadA()); executorService.shutdown(); } } class ThreadA implements Runnable { @Override public void run() { throw new RuntimeException(); } } class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("捕捉到:" + t.getName() + "的异常"); } } class MyThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler()); return thread; } }
捕捉到:Thread-0的异常
总结:这一章节比较详细的讨论了多线程的异常捕捉。
这一章节就到这里,谢谢。
-----------------------------------
从头认识java-18.2 基本的线程机制(8)多线程的异常捕捉
标签:
原文地址:http://blog.csdn.net/raylee2007/article/details/50551142