Java 小记:ScheduledExecutorService

一、创建延迟执行线程池

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);

二、自定义 Runnable或者Callable


ublic class TaskExecutor implements Runnable{


    String value;

    Integer execIndex = 0;

    public TaskExecutor(String value) {
        this.value = value;
    }

    /**
     * When an object implementing interface Runnable is used
     * to create a thread, starting the thread causes the object's
     * run method to be called in that separately executing
     * thread.
     * 

* The general contract of the method run is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { try { Thread.sleep(3000); }catch (Exception e) { e.printStackTrace(); } execIndex += 1; Date now = new Date(); DateFormat df2 = DateFormat.getDateTimeInstance(); System.out.println("执行时间:" + df2.format(now) + ",线程:" + Thread.currentThread().getName() + ",index:" + this.value + ",执行索引:" + execIndex); } }

三、生成Runnable,并加入到执行队列

TaskExecutor executor = new TaskExecutor(v);
final ScheduledFuture future = executorService.scheduleAtFixedRate(executor,0,2, TimeUnit.SECONDS);

注意:

ScheduledExecutorService有两个方法:

方法名 说明
scheduleAtFixedRate 举例:如果延迟时间是2s,但是具体的任务需要执行3s,显然下次执行的时候,上次的任务还需要1s才完成,所以这次的任务会等待1s后马上执行,所以就是执行的间隔时间就是变成了3秒
scheduleWithFixedDelay 举例:如果延迟时间是2s,但是具体任务需要执行3s,那么下次执行的时候,会等待上次任务结束后,再等待2s,再去执行,所以这样间隔时间就是5s执行一次

四、把生成的exectutor装进map中,方便下次根据key,取出相应的任务进行取消。
future有方法boolean cancel(boolean mayInterruptIfRunning),其中的mayInterruptIfRunning的设置,如果是true,则会立即中断程序(不管是否在执行中), false的话会等待正在执行的任务完成后再中断。

你可能感兴趣的:(Java 小记:ScheduledExecutorService)