多线程执行的程序抛出异常主线程是无法捕获的,要谨慎用,最好用Callable
ScheduledFuture<?> scheduledFuture = executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
synchronized (handlerAndTimer) {
System.out.println("定时任务执行");
if (counter++ == 5) {
throw new RuntimeException("退出当前线程");
}
}
}
}, 1, 4, TimeUnit.SECONDS);
Callable
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
Future<Object> submit = executorService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
return null;
}
});
submit.get();