ScheduledThreadPoolExecutor Java

ScheduledThreadPoolExecutor JavaJava提供的Time类可以周期性地或者延期执行任务,但是有时我们需要并行执行同样的任务,这个时候如果创建多个Time对象会给系统带来负担,解决办法是将定时任务放到线程池中执行。Java的ScheduledThreadPoolExecutor类实现了ScheduledExecutorService接口中定义的以不同方法执行任务的方法。Executors类提供了工厂方法创建ScheduledThrea

Java提供的Time类可以周期性地或者延期执行任务,但是有时我们需要并行执行同样的任务,这个时候如果创建多个Time对象会给系统带来负担,解决办法是将定时任务放到线程池中执行。Java的ScheduledThreadPoolExecutor类实现了ScheduledExecutorService接口中定义的以不同方法执行任务的方法。Executors类提供了工厂方法创建ScheduledThreadPoolExecutor,并且可以设置线程池中的线程。

假设有下面简单的Runnable类
WorkerThread.java:

package org.apache.selftest;

import java.util.Date;

public class WorkerThread implements Runnable { 
   

    private String command;

    public WorkerThread(String s) {
        this.command = s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " Start. Time = " + new Date());
        processCommand();
        System.out.println(Thread.currentThread().getName() + " End. Time = " + new Date());
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return this.command;
    }
    public static void main(String[] args){
        Thread t = new Thread(new WorkerThread("a test"));
        t.start();
    }
}

Thread-0 Start. Time = Wed Mar 08 21:41:07 CST 2017
Thread-0 End. Time = Wed Mar 08 21:41:13 CST 2017

下面的例子中worker线程将被延期10s执行上面的Rnnable类大约花费5s执行任务

ScheduledThreadPool.java:

运行上面的程序,可以得到下面的输出,由此可以确认任务在10s后才执行。

class ScheduledThreadPool {

    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

        //schedule to run after sometime
        System.out.println("Current Time = " + new Date());
        for (int i = 0; i < 3; i++) {
            Thread.sleep(1000);
            WorkerThread worker = new WorkerThread("do heavy processing");
            scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS);
        }

        //add some delay to let some threads spawn by scheduler
        Thread.sleep(30000);

        scheduledThreadPool.shutdown();
        while (!scheduledThreadPool.isTerminated()) {
            //wait for all tasks to finish
        }
        System.out.println("Finished all threads");
    }

}

Current Time = Wed Mar 08 21:43:31 CST 2017
pool-1-thread-1 Start. Time = Wed Mar 08 21:43:42 CST 2017
pool-1-thread-2 Start. Time = Wed Mar 08 21:43:43 CST 2017
pool-1-thread-3 Start. Time = Wed Mar 08 21:43:44 CST 2017
pool-1-thread-1 End. Time = Wed Mar 08 21:43:47 CST 2017
pool-1-thread-2 End. Time = Wed Mar 08 21:43:48 CST 2017
pool-1-thread-3 End. Time = Wed Mar 08 21:43:49 CST 2017
Finished all threads

注意到所有的schedule方法都返回了ScheduledFuture实例,可以用于获取线程状态信息和延迟时间。ScheduledFuture接口继承Future接口,更多信息见Java Callable Future Example.

在ScheduledExecutorService中至少有2个方法可用于周期性执行任务。

scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)

我们可以使用该方法延迟执行任务,设置任务的执行周期。时间周期从线程池中首先开始执行的线程算起,所以假设period为1s,线程执行了5s,那么下一个线程在第一个线程运行完后会很快被执行。

比如下面的代码

for (int i = 0; i <1; i++) {
    Thread.sleep(1000);
    WorkerThread worker = new WorkerThread("do heavy processing");
   // schedule task to execute at fixed rate
    scheduledThreadPool.scheduleAtFixedRate(worker, 0, 10, TimeUnit.SECONDS);
    }

输出

Current Time = Wed Mar 08 21:47:43 CST 2017
pool-1-thread-1 Start. Time = Wed Mar 08 21:47:44 CST 2017
pool-1-thread-1 End. Time = Wed Mar 08 21:47:49 CST 2017
pool-1-thread-1 Start. Time = Wed Mar 08 21:47:54 CST 2017
pool-1-thread-1 End. Time = Wed Mar 08 21:47:59 CST 2017
该方法可被用于延迟周期性执行任务,delaytime是线程停止执行到下一次开始执行之间的延迟时间,假设有下面的代码
for (int i = 0; i <1; i++) {
Thread.sleep(1000);
WorkerThread worker = new WorkerThread(“do heavy processing”);
// schedule task to execute at fixed rate
scheduledThreadPool.scheduleWithFixedDelay(worker, 0, 10, TimeUnit.SECONDS);
}
输出结果
Current Time = Wed Mar 08 21:49:26 CST 2017
pool-1-thread-1 Start. Time = Wed Mar 08 21:49:27 CST 2017
pool-1-thread-1 End. Time = Wed Mar 08 21:49:32 CST 2017
pool-1-thread-1 Start. Time = Wed Mar 08 21:49:42 CST 2017
pool-1-thread-1 End. Time = Wed Mar 08 21:49:47 CST 2017
Finished all threads

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/35066.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注