【Concurrency-ScheduledExecutorService】


簡介

線程池執行者在ThreadPoolExecutor的基礎上給咱們提供了延時(delay)執行和週期執行的功能。性能會優於Timer包。java

繼承結構

結構

參考:

ThreadPoolExecutor
Executor
ExecutorService
ScheduledExecutorService
AbstractExecutorServiceide

DEMO

package calvin;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public class TestScheduledThreadPoolExecutor {
    public static ScheduledThreadPoolExecutor executor = null;
    
    public static void main(String[] args){
        System.out.println("test ScheduledThreadPoolExecutor");
        executor = new ScheduledThreadPoolExecutor(5);
        myTask task = new myTask();
        // 2秒後執行,執行後就中止
        executor.schedule(task, 2l, TimeUnit.SECONDS);
        // 5秒後執行,執行完後每10秒再執行不會自動中止
        executor.scheduleWithFixedDelay(task, 5l, 10, TimeUnit.SECONDS);
        
    }
    
    public static class myTask implements Runnable{
        public AtomicInteger index = new AtomicInteger();
        @Override
        public void run(){
            System.out.println(System.currentTimeMillis() + "start working  thread = "+Thread.currentThread().getName() + " index =" + index.incrementAndGet());
        }
        
    }
}

小結

  1. 對於Executor對象來講他的task執行順序是根據FIFO原則來運行的
  2. 給咱們提供了定時執行任務的功能
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息