一,创建一个线程池
其中:
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor)
饱和策略执行时的具体逻辑。
protected void afterExecute(Runnable r, Throwable t)
异常后的具体逻辑。
package com.kintech.scanAF.common;
import com.kintech.common.utils.log.LogerHelper;
import java.util.concurrent.*;
/**
* @author Tyler
* @date 2019/9/12
*/
public class ThreadHelper {
//初始化线程池
private static final ExecutorService pool = new ThreadPoolExecutor(
2,
5,
60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy(){
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
LogerHelper.Write("--- "+this.getClass().getName()+"\r\n--- 队列已满,请稍后再来");
}
})
{
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
LogerHelper.Write(t.getMessage());
System.out.println(t.getMessage());
}
};
/**
* 执行线程池方法(方法在RunnableFunc文件夹中)
* @param run
*/
public static void execute(Runnable run)
{
pool.execute(run);
}
/**
* 执行线程池方法(方法在RunnableFunc文件夹中)
* @param run
*/
public static Future<?> submit(Runnable run)
{
Future<?> future = pool.submit(run);
return future;
}
}
线程池的参数介绍:
public ThreadPoolExecutor(
int corePoolSize, // 线程数量
int maximumPoolSize, // 最大线程数量
long keepAliveTime, // 线程存活时间
TimeUnit unit, //时间单位
BlockingQueue<Runnable> workQueue, // 任务队列
ThreadFactory threadFactory, // 线程创建工厂,可以给线程起名字
RejectedExecutionHandler handler) // 饱和策略
二,创建任务
package com.kintech.scanAF.common.RunnableFunc;
/**
* @author Tyler
* @date 2019/9/12
*/
public class Test implements Runnable {
private String a;
public Test(String a)
{
this.a=a;
}
@Override
public void run() {
try
{
throw new RuntimeException( "Service has error !");
}
catch (Exception e) {
throw e;
}
finally
{
a=null;
}
}
}
三,调用并获取异常
public void MainTest(String a) throws IOException {
Future<?> future = ThreadHelper.submit(new Test(a));
try {
future.get();
}
catch (Exception ex)
{
//记录日志
LogerHelper.Write(ex.getMessage());
//swing弹窗
JOptionPane.showMessageDialog(null, ex.getMessage(), "Message", JOptionPane.ERROR_MESSAGE);
}
}
|