其他
线程异常如何处理?试试这样
点击上方 Java后端,选择 设为星标
优质文章,及时送达
作者:何甜甜在吗
https://juejin.im/post/6844903997388636174
之前使用线程执行任务的时候,总是忽略了线程异常的处理,直到最近看书
线程出现异常测试
public class Task implements Runnable {
private int i;
public Task(int i) {
this.i = i;
}
@Override
public void run() {
if (i == 5) {
//System.out.println("throw exception");
throw new IllegalArgumentException();
}
System.out.println(i);
}
}
public class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
try {
new Thread(new Task(i++)).start();
} catch (Exception e) {
System.out.println("catch exception...");
}
}
}
}
Connected to the target VM, address: '127.0.0.1:64551', transport: 'socket'
0
1
2
3
4
6
7
8
9
Exception in thread "pool-1-thread-1" java.lang.IllegalArgumentException
at com.h2t.study.thread.Task.run(Task.java:21)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
线程异常处理
异常处理器:ExceptionHandler.java
private static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("异常捕获到了:" + e);
}
}
设置默认异常处理器
Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println("异常捕获到 了: " + e));
int i = 0;
while (true) {
if (i == 10) break;
Thread thread = new Thread(new Task(i++));
thread.start();
}
0
2
1
3
9
6
7
4
异常捕获到了:java.lang.IllegalArgumentException
8
设置自定义异常处理器
Thread t = new Thread(new Task(i++));
t.setUncaughtExceptionHandler(new ExceptionHandler());
0
2
4
异常捕获到了:java.lang.IllegalArgumentException
6
1
3
7
9
8
MyThreadGroup myThreadGroup = new MyThreadGroup("测试线程线程组");
Thread t = new Thread(myThreadGroup, new Task(i++))
private static class MyThreadGroup extends ThreadGroup {
public MyThreadGroup(String name) {
super(name);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("捕获到异常了:" + e);
}
}
1
2
0
4
3
6
7
8
9
捕获到异常了:java.lang.IllegalArgumentException
线程池异常处理
默认异常处理器
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new Task(i++))
自定义异常处理器
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.setThreadFactory(new MyThreadFactory());
threadPoolExecutor.execute(new Task(i++));
自定义工厂类:MyThreadFactory.java
private static class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread();
//自定义UncaughtExceptionHandler
t.setUncaughtExceptionHandler(new ExceptionHandler());
return t;
}
}
线程执行 Callable 任务
public class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
}
private static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("异常捕获到了:" + e);
}
}
}
Disconnected from the target VM, address: '127.0.0.1:64936', transport: 'socket'
0
1
2
3
4
6
7
8
9
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//将异常设置给outcome变量
outcome = t;
//设置任务的状态为EXCEPTIONAL
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
int i = 0;
while (true) {
if (i == 10) break;
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
//打印结果
try {
System.out.println(task.get());
} catch (Exception e) {
System.out.println("异常被抓住了, e: " + e);
}
}
0
1
2
3
4
异常被抓住了, e: java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException
6
7
Disconnected from the target VM, address: '127.0.0.1:50900', transport: 'socket'
8
9
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//未完成等待任务执行完成
s = awaitDone(false, 0L);
return report(s);
}
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
总结:
Callable 任务抛出的异常能在代码中通过 try-catch 捕获到,但是只有调用 get 方法后才能捕获到
如果看到这里,说明你喜欢这篇文章,请 转发、点赞。同时 标星(置顶)本公众号可以第一时间接受到博文推送。
推荐阅读
1. 采用 Vue 编写的功能强大的 Swagger-ui 页面
获取方式:点“ 在看,关注公众号 Java后端 并回复 777 领取,更多内容陆续奉上。
喜欢文章,点个在看