1.线程池原理 :伪代码
在线程池中假设最多开3个线程,当小于三个,进行创建,添加到集合中,然后不停的轮训线程集合进行执行,直到为空时,进入等待状态
public class ThreadPool { int maxCount = 3;//假设最多开只能开三个线程 AtomicInteger count =new AtomicInteger(0);// 当前开的线程数 count=0,为了线程同步,使用此api 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(); } }
2.线程池的使用,创建一个线程管理者,单例模式
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对象中 排队,10表示最多10个对象 */ 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); // 取消异步任务 } } } }
使用:
ThreadManager.getInstance().createLongPool().execute(new Runnable() { @Override public void run() { } });
时间: 2024-11-05 13:31:50