线程中异常解决策略有三大类
- 利用在Thread内的run方法中自行处理
- 为Thread对象设置异常处理Handler(UncaughtExceptionHandler)
- 获取Future对象
- 利用FutureTask
- 利用CompletableFuture
- 利用CompletableFuture
- 利用线程池的sumbit进行提交,从而获取Future对象
- 等等
package com.study;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class MultiThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
}
public static void getDataByUncaughtExceptionHandler() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
throw new RuntimeException("你好");
}
});
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace();
}
});
ThreadFactory factory = r -> {
Thread thread1 = new Thread(r);
thread1.setUncaughtExceptionHandler((t, e) -> System.out.println("记录"));
thread1.start();
return thread1;
};
factory.newThread(() -> {
throw new RuntimeException("报错");
});
}
public static void getDataByFuture() throws ExecutionException, InterruptedException {
FutureTask<Integer> task =new FutureTask<>(() -> {
Thread.sleep(5000);
int i = 1/0;
return 1;
});
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get());
}
public void getDataByCompletableFuture() throws ExecutionException, InterruptedException {
CompletableFuture future1 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("不带返回值");
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return 1;
}
}).thenApplyAsync(new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) {
return integer + 1;
}
});
try {
System.out.println(future2.get());
}catch (Exception e){
e.printStackTrace();
}
System.out.println(1);
}
public void getDataByExecutor(){
ExecutorService pool = Executors.newFixedThreadPool(10);
Future<Integer> submit = pool.submit(() -> {throw new RuntimeException("报错");});
try {
submit.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
pool.shutdown();
System.out.println(1);
}
}