ScheduledThreadExecutor定时任务线程池

版权声明:本文由李章勇老师创作,请支持原创,谢谢 https://blog.csdn.net/weixin_37654790/article/details/85264072

  ScheduledThreadPoolExecutor 继承自ThreadPoolExecutor实现了ScheduledExecutorService接口。主要完成定时或者周期的执行线程任务。

  代码如下:

package com.itszt.test3;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * ScheduledThreadExecutor,定时任务线程池
 */
public class Test3 {
    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);
        System.out.println("main开始时间:"+MyRunnable.now());
        for(int i=0;i<3;i++){
            MyRunnable myRunnable = new MyRunnable("thread-" + i);
            System.out.println(myRunnable.getName()+"开始时间:"+MyRunnable.now());
            pool.schedule(myRunnable,5, TimeUnit.SECONDS);//延时5秒执行
            //在一次调用完成和下一次调用开始之间有长度为delay的延迟
            //pool.scheduleWithFixedDelay(myRunnable,5,5,TimeUnit.SECONDS);
        }
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pool.shutdown();//7秒后不再接受执行线程
        while (!pool.isTerminated()){
            //等待所有线程结束
        }
        System.out.println("main结束时间:"+MyRunnable.now());
    }
}
class MyRunnable implements Runnable{
    private String name;

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

    public String getName() {
        return name;
    }

    @Override
    public void run() {
        System.out.println(getName()+"true start:"+now());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(getName()+"true end:"+now());
    }
    static String now(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }
}

  代码执行结果如下:

main开始时间:2018-03-24 21:08:06
thread-0开始时间:2018-03-24 21:08:06
thread-1开始时间:2018-03-24 21:08:06
thread-2开始时间:2018-03-24 21:08:06
thread-1true start:2018-03-24 21:08:11
thread-2true start:2018-03-24 21:08:11
thread-0true start:2018-03-24 21:08:11
thread-2true end:2018-03-24 21:08:14
thread-0true end:2018-03-24 21:08:14
thread-1true end:2018-03-24 21:08:14
main结束时间:2018-03-24 21:08:14  

猜你喜欢

转载自blog.csdn.net/weixin_37654790/article/details/85264072