4.线程池

2018-05-14 11:33:54 浏览数 (1)

由于不需要每次处理复杂逻辑耗时操作,比如加载网络并不需要都开启一个新的线程,可以用线程池处理,把线程存起来,用的时候在取出来,在ondestory里去销毁线程,这样就会节省内存

线程池的原理(看看就行):

代码语言:javascript复制
public class ThreadPool {	int maxCount = 3;	AtomicInteger count =new AtomicInteger(0);// 当前开的线程数  count=0	LinkedList<Runnable> runnables = new LinkedList<Runnable>();	public void execute(Runnable runnable) {		runnables.add(runnable);		if(count.incrementAndGet()<=3){			createThread();// 最大开三个线程		}	}	private void createThread() {		new Thread() {			@Override			public void run() {				super.run();				while (true) {					// 取出来一个异步任务					if (runnables.size() > 0) {						Runnable remove = runnables.remove(0); //在集合中移除第一个对象 返回值正好是移除的对象						if (remove != null) {							remove.run();						}					}else{						//  等待状态   wake();					}				}			}		}.start();	}}

线程池的用法:在本项目中新建一个类管理线程池,主要用的就是ThreadPoolExecutor这个类

代码语言:javascript复制
public class ThreadManager {	private ThreadManager() {	}	private static ThreadManager instance = new ThreadManager();	private ThreadPoolProxy longPool;	private ThreadPoolProxy shortPool;	public static ThreadManager getInstance() {		return instance;	}	// 联网比较耗时	// 开启线程数一般是cpu的核数*2 1	public synchronized ThreadPoolProxy createLongPool() {		if (longPool == null) {			longPool = new ThreadPoolProxy(5, 5, 5000L);		}		return longPool;	}	// 操作本地文件	public synchronized ThreadPoolProxy createShortPool() {		if(shortPool==null){			shortPool = new ThreadPoolProxy(3, 3, 5000L);		}		return shortPool;	}	public class ThreadPoolProxy {		private ThreadPoolExecutor pool;		private int corePoolSize;		private int maximumPoolSize;		private long time;		public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long time) {			this.corePoolSize = corePoolSize;			this.maximumPoolSize = maximumPoolSize;			this.time = time;		}		/**		 * 执行任务		 * @param runnable		 */		public void execute(Runnable runnable) {			if (pool == null) {				// 创建线程池				/*				 * 1. 线程池里面管理多少个线程2. 如果排队满了, 额外的开的线程数3. 如果线程池没有要执行的任务 存活多久4.				 * 时间的单位 5 如果 线程池里管理的线程都已经用了,剩下的任务 临时存到LinkedBlockingQueue对象中 排队				 */				pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,						time, TimeUnit.MILLISECONDS,						new LinkedBlockingQueue<Runnable>(10));			}			pool.execute(runnable); // 调用线程池 执行异步任务		}		/**		 * 取消任务		 * @param runnable		 */		public void cancel(Runnable runnable) {			if (pool != null && !pool.isShutdown() && !pool.isTerminated()) {				pool.remove(runnable); // 取消异步任务			}		}	}}

0 人点赞