新建多线程工具类
public class CommonAsynThread<R extends Object> {
private ExecutorService executor;
/**
* @使用案例 new
* CommonCallableFuture<List<Integer>>(executor).createCallableFuture(()->intList.add(9));
* @传入要执行的方法即可:例如:()->intList.add(9)
* @param params
* @throws ExecutionException
* @throws InterruptedException
*/
public CommonAsynThread() {
super();
}
public CommonAsynThread(ExecutorService executor) {
super();
this.executor = executor;
}
public ExecutorService getExecutor() {
return executor;
}
public void setExecutor(ExecutorService executor) {
this.executor = executor;
}
/**
* createCallableFuture:没有返回值的异步方法
*
* @param jobTaskFuntion
* @return
* @throws InterruptedException
* @throws ExecutionException
*/
public void createRunnable(JobExeTaskFuntion jobTaskFuntion) {
this.getExecutor().submit(new UserRunnable(jobTaskFuntion));
}
/**
* createCallableFuture:有返回值的异步方法
*
* @param jobTaskFuntion
* @return
* @throws InterruptedException
* @throws ExecutionException
*/
public Future<R> createCallableFuture(JobFutureTaskFuntion jobTaskFuntion) throws InterruptedException, ExecutionException {
Future<R> future = this.getExecutor().submit(new UserCallable(jobTaskFuntion));
return future;
}
/**
* UserRunnable:无返回值的线程
*
* @author
*
*/
class UserRunnable implements Runnable {
private JobExeTaskFuntion jobFuntion;
public JobExeTaskFuntion getJobFuntion() {
return jobFuntion;
}
public void setJobFuntion(JobExeTaskFuntion jobFuntion) {
this.jobFuntion = jobFuntion;
}
public UserRunnable(JobExeTaskFuntion jobFuntion) {
super();
this.jobFuntion = jobFuntion;
}
@Override
public void run() {
jobFuntion.execute();
}
}
/**
* UserCallable:有返回值的线程
*
* @author
*
*/
class UserCallable implements Callable<R> {
private JobFutureTaskFuntion jobTaskFuntion;
public JobFutureTaskFuntion getJobTaskFuntion() {
return jobTaskFuntion;
}
public void setJobTaskFuntion(JobFutureTaskFuntion jobTaskFuntion) {
this.jobTaskFuntion = jobTaskFuntion;
}
public UserCallable(JobFutureTaskFuntion jobTaskFuntion) {
super();
this.jobTaskFuntion = jobTaskFuntion;
}
@Override
@SuppressWarnings("unchecked")
public R call() throws Exception {
return (R) jobTaskFuntion.execute();
}
}
/**
* JobExeFuntion:无返回值
*
* @author
*
*/
@FunctionalInterface
public interface JobExeTaskFuntion {
void execute();
}
/**
* JobTaskFuntion:有返回值
*
* @author
*
*/
@FunctionalInterface
public interface JobFutureTaskFuntion {
Object execute();
}
使用多线程工具类
先定义一个线程池
ExecutorService executor = Executors.newFixedThreadPool(lineStationNumListMap.size() * 2);
传入线程池即可使用,看下面
new CommonAsynThread<Object>(executor).createRunnable(() -> {
//.......你的代码逻辑........
});
// 最后关闭线程池
executor.shutdown();