/*
使用方法
ThreadManager.getThreadPoolProxy().execute(runnable);
runnable就是之前run方法里面的东西
*/
public class ThreadManager {
//创建一个可以去调用线程池运行的对象
private static ThreadPoolProxy threadPoolProxy;
//找一个同步的对象
private static Object object=new Object();
//拿对象,有就用,没有就new
public static ThreadPoolProxy getThreadPoolProxy(){
synchronized (object){
if(threadPoolProxy==null){
threadPoolProxy=new ThreadPoolProxy(5,5,5L);
}
return threadPoolProxy;
}
//核心线程数
private int corePoolSize;
//最大线程数
private int maximumPoolSize;
//存活时间
private long keepAliveTime;
private ThreadPoolExecutor threadPoolExecutor;
//由构造函数传入,不要写死
public ThreadPoolProxy(int corePoolSize,int maximumPoolSize,long keepAliveTime){
this.corePoolSize=corePoolSize;
this.maximumPoolSize=maximumPoolSize;
this.keepAliveTime=keepAliveTime;
}
//子线程中运行的任务
public void exectue(Runnable runnable){
if (runnable!=null){
if(threadPoolExecutor==null){
//任务不为空,new一个线程池对象
threadPoolExecutor=new ThreadPoolExecutor(
//核心线程数
corePoolSize,
//最大线程数
maximumPoolSize,
//线程存活时间
keepAliveTime,
//线程存活时间单位
TimeUnit.MILLISECONDS,
//工作队列
new LinkedBlockingQueue<Runnable>(),
//默认线程对象
Executors.defaultThreadFactory(),
//线程异常处理对象
new ThreadPoolExecutor.AbortPolicy());
}
threadPoolExecutor.execute(runnable);
}
}
/*
从线程池中移除子线程中执行的任务操作
*/
public void cancel(Runnable runnable){
//任务不为空,threadPoolExecutor不为空,线程池正在运行(没挂掉)
if(runnable!=null&&threadPoolExecutor!=null&&!threadPoolExecutor.isShutdown){
threadPoolExecutor.getQueue().remove(runnable);
}
}
}
}
使用方法
ThreadManager.getThreadPoolProxy().execute(runnable);
runnable就是之前run方法里面的东西
*/
public class ThreadManager {
//创建一个可以去调用线程池运行的对象
private static ThreadPoolProxy threadPoolProxy;
//找一个同步的对象
private static Object object=new Object();
//拿对象,有就用,没有就new
public static ThreadPoolProxy getThreadPoolProxy(){
synchronized (object){
if(threadPoolProxy==null){
threadPoolProxy=new ThreadPoolProxy(5,5,5L);
}
return threadPoolProxy;
}
}
//核心线程数
private int corePoolSize;
//最大线程数
private int maximumPoolSize;
//存活时间
private long keepAliveTime;
private ThreadPoolExecutor threadPoolExecutor;
//由构造函数传入,不要写死
public ThreadPoolProxy(int corePoolSize,int maximumPoolSize,long keepAliveTime){
this.corePoolSize=corePoolSize;
this.maximumPoolSize=maximumPoolSize;
this.keepAliveTime=keepAliveTime;
}
//子线程中运行的任务
public void exectue(Runnable runnable){
if (runnable!=null){
if(threadPoolExecutor==null){
//任务不为空,new一个线程池对象
threadPoolExecutor=new ThreadPoolExecutor(
//核心线程数
corePoolSize,
//最大线程数
maximumPoolSize,
//线程存活时间
keepAliveTime,
//线程存活时间单位
TimeUnit.MILLISECONDS,
//工作队列
new LinkedBlockingQueue<Runnable>(),
//默认线程对象
Executors.defaultThreadFactory(),
//线程异常处理对象
new ThreadPoolExecutor.AbortPolicy());
}
threadPoolExecutor.execute(runnable);
}
}
/*
从线程池中移除子线程中执行的任务操作
*/
public void cancel(Runnable runnable){
//任务不为空,threadPoolExecutor不为空,线程池正在运行(没挂掉)
if(runnable!=null&&threadPoolExecutor!=null&&!threadPoolExecutor.isShutdown){
threadPoolExecutor.getQueue().remove(runnable);
}
}
}
}