根据 CPU 内核数计算出合理的线程并发数,线程池管理和关闭。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
public class ThreadManagerUtil { public static ThreadPool instance;
public static ThreadPool getInstance() { if (instance == null) { synchronized (ThreadManagerUtil.class) { if (instance == null) { int cpuNum = Runtime.getRuntime().availableProcessors(); int threadNum = cpuNum * 2 + 1; instance = new ThreadPool(threadNum-1, threadNum, Integer.MAX_VALUE); } } } return instance; }
public static class ThreadPool { private ThreadPoolExecutor mExecutor; private int corePoolSize; private int maximumPoolSize; private long keepAliveTime;
private ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) { this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.keepAliveTime = keepAliveTime; }
public void execute(Runnable runnable) { if (runnable == null) { return; } if (mExecutor == null) { mExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { super.rejectedExecution(r, e); } } ); } mExecutor.execute(runnable); }
public void cancel(Runnable runnable) { if (mExecutor != null) { mExecutor.getQueue().remove(runnable); } }
public void shutdown(){ mExecutor.shutdown(); } } }
|