public class TestTimerTask{
public static void main(String[] args){
Timer timer =newTimer();
timer.schedule(newTimerTask(){
@Override
public void run(){
System.out.println("Timer Task");
出现一场可能导致整个服务关闭
thrownewRuntimeException();}},0);}}
使用ThreadPool不会导致整个服务关闭,新提交的任务还是可以执行
public class TestThreadPool{
public static void main(String[] args) throws Exception {
ScheduledThreadPoolExecutor executor =newScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(newTask(),0,5, TimeUnit.MILLISECONDS);
Thread.sleep(3000L);//新增的任务还是可以执行
executor.submit(newTask());}
static class Task implements Runnable{
@Override
public void run(){
System.out.println("test runnable");thrownewRuntimeException();}}}