代码写了一个线程池的Manager,主要用于Android线程管理,并创建了两个线程池,用于请求服务器和访问本地缓存文件。
1 package com.kevin.threadTest.manager; 2 3 import java.util.concurrent.LinkedBlockingQueue; 4 import java.util.concurrent.ThreadPoolExecutor; 5 import java.util.concurrent.TimeUnit; 6 7 /** 8 * 管理线程池 9 * 10 * @author kevin11 * 12 */13 public class ThreadManager {14 private ThreadManager() {15 16 }17 18 private static ThreadManager instance = new ThreadManager();19 private ThreadPoolProxy longPool;20 private ThreadPoolProxy shortPool;21 22 public static ThreadManager getInstance() {23 return instance;24 }25 26 // 联网比较耗时27 // cpu的核数*2+128 public synchronized ThreadPoolProxy createLongPool() {29 if (longPool == null) {30 longPool = new ThreadPoolProxy(5, 5, 5000L);31 }32 return longPool;33 }34 // 操作本地文件35 public synchronized ThreadPoolProxy createShortPool() {36 if(shortPool==null){37 shortPool = new ThreadPoolProxy(3, 3, 5000L);38 }39 return shortPool;40 }41 42 public class ThreadPoolProxy {43 private ThreadPoolExecutor pool;44 private int corePoolSize;45 private int maximumPoolSize;46 private long time;47 48 public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long time) {49 this.corePoolSize = corePoolSize;50 this.maximumPoolSize = maximumPoolSize;51 this.time = time;52 53 }54 /**55 * 执行任务56 * @param runnable57 */58 public void execute(Runnable runnable) {59 if (pool == null) {60 // 创建线程池61 /*62 * 1. 线程池里面管理多少个线程2. 如果排队满了, 额外的开的线程数3. 如果线程池没有要执行的任务 存活多久4.63 * 时间的单位 5 如果 线程池里管理的线程都已经用了,剩下的任务 临时存到LinkedBlockingQueue对象中 排队64 */65 pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,66 time, TimeUnit.MILLISECONDS,67 new LinkedBlockingQueue(10));68 }69 pool.execute(runnable); // 调用线程池 执行异步任务70 }71 /**72 * 取消任务73 * @param runnable74 */75 public void cancel(Runnable runnable) {76 if (pool != null && !pool.isShutdown() && !pool.isTerminated()) {77 pool.remove(runnable); // 取消异步任务78 }79 }80 }81 }
调用者的代码片段:
1 // 请求服务器 获取服务器上数据 进行判断 2 // 请求服务器 返回一个结果 3 ThreadManager.getInstance().createLongPool().execute(new Runnable() { 4 5 @Override 6 public void run() { 7 SystemClock.sleep(2000); 8 final LoadResult result = load(); 9 UiUtils.runOnUiThread(new Runnable() { 10 11 @Override 12 public void run() { 13 if (result != null) { 14 state = result.getValue(); 15 showPage(); // 状态改变了,重新判断当前应该显示哪个界面 16 } 17 } 18 }); 19 } 20 });
代码可供初学者参考,也可直接拿去应用到项目中,应用中如有问题,请大家指正。