ScheduledThreadPoolExecutor Usage

refs:

 https://blog.csdn.net/wenzhi20102321/article/details/78681379

对比一下Timer和ScheduledThreadPoolExecutor:

TimerScheduledThreadPoolExecutor
单线程 多线程
单个任务执行时间影响其他任务调度 多线程,不会影响
基于绝对时间 基于相对时间
一旦执行任务出现异常不会捕获,其他任务得不到执行 多线程,单个任务的执行不会影响其他线程

所以,在JDK1.5之后,应该没什么理由继续使用Timer进行任务调度了。

ScheduledThreadPoolExecutor usage: 
ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);
scheduled.scheduledAtFixedRate(new Runnable() {
    @Override
    public void run() {
        Log.e("wegeh");
    }
}, 0, 40, TimeUnit.MILLISECONDS);  // 0表示首次执行任务的延迟时间,40表示每次执行任务的间隔时间,
TimeUnit.MILLISECONDS执行的时间间隔数值单位

 

ScheduledThreadPoolExecutor的使用

下面用一个具体的例子来说明ScheduledThreadPoolExecutor的使用:

public class ScheduledThreadPoolTest {

    public static void main(String[] args) throws InterruptedException {
        // 创建大小为5的线程池
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

        for (int i = 0; i < 3; i++) {
            Task worker = new Task("task-" + i);
            // 只执行一次
//          scheduledThreadPool.schedule(worker, 5, TimeUnit.SECONDS);
            // 周期性执行,每5秒执行一次
            scheduledThreadPool.scheduleAtFixedRate(worker, 0,5, TimeUnit.SECONDS);
        }

        Thread.sleep(10000);

        System.out.println("Shutting down executor...");
        // 关闭线程池
        scheduledThreadPool.shutdown();
        boolean isDone;
        // 等待线程池终止
        do {
            isDone = scheduledThreadPool.awaitTermination(1, TimeUnit.DAYS);
            System.out.println("awaitTermination...");
        } while(!isDone);

        System.out.println("Finished all threads");
    }


}


class Task implements Runnable {

    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("name = " + name + ", startTime = " + new Date());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("name = " + name + ", endTime = " + new Date());
    }

}

 

from api doc:

public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {
    static class CustomTask<V> implements RunnableSchedluedFuture<V> {...}
    
    protected <V> RunnableSchedluedFuture<V> decorateTask(Runnable r, RunnableSchedluedFuture<V> task) {
        return new CustomTask<V> (r, task);
    }

    protected <V> RunnableSchedluedFuture<V> decorateTask(Callable<V> c, RunnableSchedluedFuture<V task) {
        return new CustomTask<V>(c, task);
    }
       // ... add constructors, etc.
}

 

posted @ 2019-03-18 11:03  petercao  阅读(339)  评论(0编辑  收藏  举报