为什么要用线程池管理线程?那是因为不停的创建线程是非常耗费资源的的一种方法,所以就需要对它进行管理
public class ThreadManager {
private ThreadManager() {
}
private static ThreadManager instance = new ThreadManager();
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private ThreadPoolProxy longPool;
private ThreadPoolProxy shortPool;
public static ThreadManager getInstance() {
return instance;
}
//建立5个线程,最多额外开5线程
public synchronized ThreadPoolProxy createLongPool() {
if (longPool == null) {
longPool = new ThreadPoolProxy(5, 5);
}
return longPool;
}
// 根据cpu的核数建立合适的线程池
public synchronized ThreadPoolProxy createNormalPool() {
if(shortPool==null){
shortPool = new ThreadPoolProxy(CORE_POOL_SIZE,MAXIMUM_POOL_SIZE);
}
return shortPool;
}
public class ThreadPoolProxy {
private ThreadPoolExecutor pool;
private int corePoolSize;
private int maximumPoolSize;
public ThreadPoolProxy(int corePoolSize, int maximumPoolSize) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
}
/**
* 执行任务
* @param runnable
*/
public void execute(Runnable runnable) {
if (pool == null) {
// 创建线程池
/*
* 1. 线程池里面管理多少个线程
* 2. 如果排队满了, 额外的开的线程数
* 3. 如果线程池没有要执行的任务 存活多久
* 4. 时间的单位
* 5. 如果 线程池里管理的线程都已经用了,剩下的任务 临时存到LinkedBlockingQueue对象中 排队
*/
pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
KEEP_ALIVE, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(10));
}
pool.execute(runnable); // 调用线程池 执行异步任务
}
/**
* 取消任务
* @param runnable
*/
public void cancel(Runnable runnable) {
if (pool != null && !pool.isShutdown() && !pool.isTerminated()) {
pool.remove(runnable); // 取消异步任务
}
}
}
}
使用的方法很简单哈
写一个类实现Runnable的run方法,进行耗时操作
public class MyRunnable implements Runnable {
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
ThreadManager.getInstance().createNormalPool().execute(new MyRunnable());