java線程池的一些簡單功能,后續會更新,代碼不多,很好理解
package com.rbac.thread; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; /** * 自定義線程池 * * @author xl,lang * */ public class MyExecutorService { // 初始化線程 protected List<InitThread> initThreads; // 執行任務列表 protected BlockingQueue<Runnable> taskQueues; // 線程執行狀態 protected volatile boolean threadState = true; /* * // 當前線程的活躍數 public AtomicInteger activeCount; public Lock lock=new * ReentrantLock(); // 最小活躍數 public int threadMinSize = 0; // 最大線程數 public * int threadMaxSize = 0; // 初始話線程數 public int threadInitSize = 0; */ /** * 線程初始化方法 * * @param threadMaxSize * @param threadInitSize * @param taskQueueSize */ /* * public MyExecutorService(int threadMaxSize, int threadMinSize, int * threadInitSize, int taskQueueSize) { this.taskQueues = new * LinkedBlockingDeque<Runnable>(taskQueueSize); if (threadInitSize > 0 && * threadInitSize < threadMaxSize) { this.initThreads = new ArrayList<>(); * for (int i = 0; i < threadInitSize; i++) { InitThread init = new * InitThread(); init.start(); initThreads.add(init); } * * } * * } */ /** * 線程初始化方法 * * @param threadMaxSize * @param threadInitSize * @param taskQueueSize */ public MyExecutorService(int threadInitSize, int taskQueueSize) { this.taskQueues = new LinkedBlockingDeque<Runnable>(taskQueueSize); if (threadInitSize > 0) { this.initThreads = new ArrayList<>(); for (int i = 0; i < threadInitSize; i++) { InitThread init = new InitThread(); init.start(); initThreads.add(init); } } } // 添加任務 public boolean exeute(Runnable task) throws InterruptedException { return this.taskQueues.offer(task, 60, TimeUnit.SECONDS); } /** * 初始化線程 * * @author xl,lang * */ class InitThread extends Thread { @Override public void run() { while (threadState || taskQueues.size() > 0) { Runnable runable = taskQueues.poll(); if (null != runable) { runable.run(); } } } } // 關閉線程池 public void shutdown() { this.threadState = false; } public static void main(String[] args) { MyExecutorService es = new MyExecutorService(2, 5); for (int i = 0; i < 100; i++) { final int a = i; try { es.exeute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + "執行" + a); } }); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } es.shutdown(); } }