先上答案:
1⃣️如果是execute方法提交任务,则抛出异常,如果是submit提交任务,如果调用了get()获取FutureTask的返回结果,则会抛出异常,如果没有调用get()方法则不会抛异常.
2⃣️异常的线程会从线程池中移除
以下是测试代码:
package com.memory.studydemo.threadpool;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
public static void main(String[] args) throws InterruptedException {
ThreadPoolTaskExecutor threadPoolTaskExecutor = buildThreadPoolExecutor();
threadPoolTaskExecutor.execute(()-> hello("execute"));
TimeUnit.SECONDS.sleep(1);
System.out.println("=================");
//submit方法的返回值类型是Future
Future<?> submit = threadPoolTaskExecutor.submit(() -> hello("submit"));
try {
//调用get()方法获取执行结果,此步不调用则submit方式不会抛出异常
submit.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private static void hello(String name) {
String printStr = "【thread-name:"+Thread.currentThread().getName()+" ,执行方式:"+name+"】";
System.out.println(printStr);
int a =9/0;
}
private static ThreadPoolTaskExecutor buildThreadPoolExecutor(){
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("Memor