zoukankan      html  css  js  c++  java
  • timer和ScheduledThreadPoolExecutor

    在JDK1.5的时候在java.util.concurrent并发包下引入了ScheduledThreadPoolExecutor类,引入它的原因是因为Timer类创建的延迟周期性任务存在一些缺陷, ScheduledThreadPoolExecutor继承了ThreadPoolExecutor,并且实现了ScheduledExecutorService接口, ScheduledThreadPoolExecutor也是通过schedule方法执行Runnable任务的。

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5); //创建5个执行线程

    Runnable runnable = new Runnable() {

    @Override
    public void run() {
    String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
    System.out.println("Now Time : " + time);
    }
    };

    executor.scheduleWithFixedDelay(runnable, 2, 3, TimeUnit.SECONDS);//2是首次延迟时间,3是定期执行的间隔时间

    timer的缺陷:是单线程的,如果一个任务的执行耗时,那么其他任务会出现实效的问题;不捕获异常,timetask抛出异常会导致整个timer不会执行,新的任务不会被调度;timer是基于绝对时间的,对系统时间比较敏感,而ScheduledThreadPoolExecutor是基于相对时间,他在内部存储了距离下次执行所需要的时间。

  • 相关阅读:
    NetBeans 时事通讯(刊号 # 143 Apr 19, 2011)
    道道道
    係要听ROCK N' ROLL
    JPA 缓存与应用集群
    NetBeans 时事通讯(刊号 # 144 Apr 28, 2011)
    係要听ROCK N' ROLL
    道道道
    JPA 缓存与应用集群
    twemproxy (nutcracker) Build Status
    Java 与 C进行Socket通讯
  • 原文地址:https://www.cnblogs.com/zyzg/p/7649315.html
Copyright © 2011-2022 走看看