Timer与ScheduledThreadPoolExecutor

/**
 *
 * 定义Timer的任务器
 * @author gino
 * 2021-11-30
 */
public class TestTask  extends TimerTask {

    private Boolean error;

    public TestTask(boolean error){
        this.error=error;
    }
    @Override
    public void run() {
        System.out.println("runing task");
        if (error) {
            throw new RuntimeException();
        }
    }
}
package com.ljq.mydemo.thread.pool.timer;

import java.util.Timer;

/**
 *
 * 用Timer定时任务则会出现以下问题
 *
 * 1.当其中一个Task异常的时候整个Timer 会被认定为取消状态 从而导致整个的Timer都会被取消
 * 2.当周期性的执行某两个任务的时候, 如果某个任务的执行时间时间大于所其他的执行任务的执行周期, 那个这个执行任务的执行会影响其他的执行任务的定时的精准行
 *
 * 应该使用线程池的方式创建
 *  optimize
 * @author gino
 * 2021-11-30
 */
public class TestMain {

    private static Timer timer=new Timer();

    public static void main(String[] args) throws InterruptedException {

        TestTask  task1=new TestTask(true);
        System.out.println("start task1===========");
        timer.schedule(task1,1);

        
        Thread.sleep(5000);
        TestTask  task2=new TestTask(false);
        timer.schedule(task2,1);
        System.out.println("end task2===========");
    }
}

package com.ljq.mydemo.thread.pool.timer;


import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 * 固定周期执行
 *
 * 正常: 此线程池为40毫秒执行一次,主线程等待5000毫秒最多执行  125次就会退出
 * 异常:当有线程抛出异常以后 线程池会停止执行,但是不会抛出异常, 主线程正常执行
 *
 * 使用线程池优化线程
 * @author gino
 * 2021-11-30
 */
public class OptimizeTask {
    public static volatile int i=1;

    public static void main(String[] args) throws InterruptedException {
        ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);
        //0表示首次执行任务的延迟时间,40表示每次执行任务的间隔时间,TimeUnit.MILLISECONDS执行的时间间隔数值单位

        scheduled.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("start ......"+i);
                if(i%2==0){
                    throw new RuntimeException();
                }
                System.out.println("end ......"+i);
                i++;
            }
        }, 0, 40, TimeUnit.MILLISECONDS);
        Thread.sleep(5000);
        scheduled.shutdown();
    }

}

package com.ljq.mydemo.thread.pool.timer;


import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 *固定延时执行
 * 使用线程池不会造成当执行线程失败的时候,导致主线程也异常退出
 *
 * 使用线程池优化线程
 * @author gino
 * 2021-11-30
 */
public class OptimizeTask2 {
    public static volatile int i=1;

    public static void main(String[] args) throws InterruptedException {
        ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);
        //0表示首次执行任务的延迟时间,40表示每次执行任务的间隔时间,TimeUnit.MILLISECONDS执行的时间间隔数值单位
        scheduled.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("start ......"+i);
                if(i>3){
                    throw new RuntimeException();
                }
                System.out.println("end ......"+i);
                i++;
            }
        }, 0, 50, TimeUnit.MILLISECONDS);



        Thread.sleep(6000);

        System.out.println(scheduled.isShutdown());

        scheduled.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("start2 ......"+i);
                if(i>6){
                    throw new RuntimeException();
                }
                System.out.println("end2 ......"+i);
                i++;
            }
        }, 0, 50, TimeUnit.MILLISECONDS);

        //要让主线程等待,否则主线程退出就无法看第二个线程的结果了
        Thread.sleep(5000);

        scheduled.shutdown();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ScheduledThreadPoolExecutorTimer是用于实现定时任务调度的类。二者有一些相似之处,但也有很多不同之处。 ScheduledThreadPoolExecutorJava5引入的类,它实现了ExecutorService接口,提供了更强大和灵活的定时任务调度功能。它可以执行一次性任务,也可以执行循环任务,支持延迟执行和周期性执行。相比之下,Timer类只能执行一次性任务或循环任务,并且不支持延迟执行。 使用ScheduledThreadPoolExecutor可以更好地控制任务的执行。它提供了更多的参数来控制任务的执行时间、间隔和延迟。同时,ScheduledThreadPoolExecutor还提供了更多的方法来管理和监控任务的状态,例如取消任务、获取任务执行结果等。 另外,ScheduledThreadPoolExecutor采用了线程池的方式管理线程,可以更好地管理并发执行的任务。它可以根据需要创建和回收线程,并且可以限制同时执行的任务数量,提了性能和资源利用率。而Timer类则是在一个单独的线程中执行任务,不能灵活地管理线程。 总的来说,如果你需要更灵活、可控、性能的定时任务调度功能,推荐使用ScheduledThreadPoolExecutor。它提供了更多的功能和扩展性,适合在新的代码中使用。而如果你只是简单地执行一次性任务或循环任务,并且不需要太多的控制和管理,可以考虑使用Timer类。 来源: https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html 来源: https://www.binghe.io/archives/188.html 来源: https://www.binghe.io/archives/188.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值