背景
平时自己在使用的ThreadPoolExecutor的时候,提交任务用submit和execute方法用的比较随意,知道当需要获取返回结果的时候用submit。但当并不需要结果的时候submit和execute用得比较随意。在一次使用submit的时候并没有获得预期结果,但也没有异常日志输出。在进行一波调试之后,任务在线程中出现异常了,但也并未出现异常抛出的情况。
代码测试
1、先用execute 查看当出现异常的情况
public class ThreadPoolTest {
private static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(500),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("submit-execute-test");
return thread;
}
}
);
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int j = i;
executor.execute(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2 + random.nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (j % 2 != 0) {
throw new RuntimeException("线程错误");
}