版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37279783/article/details/82114823
//线程池逻辑类
public class TaskExecutorService {
// private final ExecutorService pool;
private final ThreadPoolExecutor pool;
private static TaskExecutorService instance;
//线程池大小,即每次最多允许开启几个线程执行转换操作
private static final int THREAD_SIZE = 5;
public static TaskExecutorService getInstance() {
if (instance == null) {
instance = new TaskExecutorService();
}
return instance;
}
public TaskExecutorService() {
pool = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(5),new ThreadPoolExecutor.CallerRunsPolicy());
// pool = Executors.newFixedThreadPool(THREAD_SIZE);
}
/**
* 开启新线程,执行转换操作
* @param pxsl
*/
public void execute(MetaPxsl pxsl,String version) {
try {
// Future future = pool.submit(new TaskExecutor(pxsl,version));
pool.execute(new TaskExecutor(pxsl,version));
// System.out.println(future.get());
System.out.println("线程池中线程数目:"+pool.getPoolSize()+",队列中等待执行的任务数目:"+
pool.getQueue().size()+",已执行玩别的任务数目:"+pool.getCompletedTaskCount());
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void shutdown() {
pool.shutdown();
}
}
//线程任务业务执行类
public class TaskExecutor implements Runnable,Serializable {
private MetaPxsl pxsl;
private String version;
public TaskExecutor(MetaPxsl pxsl,String version) {
this.pxsl = pxsl;
this.version = version;
}
@Override
public void run() {
try {
IJobLbService iJobLbService = (IJobLbService) ContextLoader.getCurrentWebApplicationContext().getBean("iJobLbService");
JobLb jobLb = iJobLbService.getById(pxsl.getJoblbId());
Class cls = Class.forName(jobLb.getClassPath());
Method execute = cls.getDeclaredMethod("execute",String.class,String.class);
execute.invoke(cls.newInstance(),pxsl.getId(),version);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//线程池使用方法
TaskExecutorService taskExecutorService = new TaskExecutorService();
taskExecutorService.execute(pxsl,version);
//拒绝处理任务时的策略,有以下四种取值:
ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务