1. 程式人生 > >ScheduledThreadExecutor定時任務線程池

ScheduledThreadExecutor定時任務線程池

get exe ted 技術分享 with static end 長度 sim

  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  

ScheduledThreadExecutor定時任務線程池