ScheduledThreadExecutor定时任务线程池

ScheduledThreadExecutor定时任务线程池

  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  
posted @ 2018-03-24 21:10 奔跑在梦想的道路上 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值