ScheduledExecutorService实现多线程任务调度,替代Timer

本文深入探讨了Java中Timer的局限性,如不支持多线程和无法捕获异常等问题,以及ScheduledExecutorService作为其完美替代方案的优势。通过具体代码示例,展示了ScheduledExecutorService如何实现更稳定、高效的定时任务调度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要原因例如以下:

Timer不支持多线程。全部挂在Timer下的任务都是单线程的,任务仅仅能串行运行。假设当中一个任务运行时间过长。会影响到其它任务的运行,然后就可能会有各种接踵而来的问题。
Timer的线程不捕获异常。TimerTask假设抛出异常,那么Timer唯一的进程就会挂掉,这样挂在Timer下的全部任务都会无法继续运行。
为了弥补Timer的缺陷,jdk1.5中引入了并发包。这里面提供的ScheduledExecutorService。详细实现类是:ScheduledThreadPoolExecutor。ScheduledThreadPoolExecutor支持多线程。同一时候在线程中对异常进行了捕获。

所以是Timer的完美替换者。
下面是楼主手写测试Demo 可运行观察下


import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test {



    public static void main(String[] args) {
        long now = System.currentTimeMillis();
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DAY_OF_MONTH, 1);
        long torromow = cal.getTime().getTime();//获取设定时间
        long initialDelay = torromow - now;//减去当前时间 获取需要间隔多少毫秒执行
        //距离0点还有多少毫秒
        System.err.println("initialDelay:"+initialDelay);

        Runnable runnable1 = new Runnable() {
            public void run() {
                System.err.println("任务1启动!"+new Date().toLocaleString());
                try {
                    Thread.sleep(0*1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        };
        Runnable runnable2 = new Runnable() {
            public void run() {
                System.err.println("任务2启动!"+new Date().toLocaleString());


            }
        };
        Runnable runnable3 = new Runnable() {
            public void run() {
                System.err.println("任务3启动!"+new Date().toLocaleString());


            }
        };
        // TODO Auto-generated method stub
        ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
        //第一个参数为runnable  第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间,第四个参数为时间单位
        service.scheduleAtFixedRate(runnable1, 0,3, TimeUnit.SECONDS);
        service.scheduleAtFixedRate(runnable3, 0,3, TimeUnit.SECONDS);
        service.scheduleAtFixedRate(runnable2,initialDelay,1000 * 60 * 60 * 24, TimeUnit.MILLISECONDS);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值