標籤:oid second ble repo 直接 print keepalive adp row
通過Executor建立線程池
Executor.newFixedTreadPool
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
內部通過new ThreadPoolExecutor建立線程池
返回一個固定數量的線程池。如果線程池中有空閑線程則直接交給空閑線程執行。如果沒有將任務放到隊列
Executor.newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
返回一個線程的線程池,如有空閑則執行,沒有則將任務放到隊列中等待
Executor.newCachedTreadPool
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
返回一個根據實際情況調整線程個數的線程池塘 不限制最大線程數,如果有空閑線程則直接交給空線程執行 沒有則建立,線程空閑超過60秒則指定回收
Exucutor.newScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }
public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }
public class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService
可以發現還是通過ThreaPoolExecutor實現 隊列使用DeayedWorkQueue
返回SchededExecutoryService對象
可以實現定時任務
public static void main(String[] args) throws InterruptedException { ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(1); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("11"); } },1,3,TimeUnit.SECONDS); // 1為延遲多久執行 3為輪訓時間 TimeUnit.seconds為 時間單位 }
自訂線程池
ThreadPoolExecutor的建構函式
public ThreadPoolExecutor(int corePoolSize,//核心線程數量 (預設線程數量) int maximumPoolSize,//最大線程數量(如果沒有超過最大線程數量 沒有空閑線程則建立) long keepAliveTime,//線程的生命週期 TimeUnit unit,//keepAliveTime時間單位 BlockingQueue<Runnable> workQueue,//若沒有空閑線程 任務放置的隊列 ThreadFactory threadFactory, RejectedExecutionHandler handler)//隊列有有界隊列。如果任務隊列滿了以後。拒絕的任務的自訂動作
java線程池