前言
在我们的业务中很可能会碰到需要执行一段时间的任务,并且如果同步的话就会造成一些无谓的等待。因此可以使用异步调用的方法,不阻塞当前其他任务的执行。
小栗子
首先我们先要创建一个线程池,可以根据自己的需求创建,什么IO密集型参数设置,CPU密集型参数的设置。这里我们仅仅想让10个任务一起跑。
ExecutorService threadPool = new ThreadPoolExecutor(
10,
10,
0,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadPoolExecutor.AbortPolicy());
然后模拟下需要异步调用的业务的执行,这里我的n给不同线程设置了不同的执行时间,在判断超时时,会有部分线程无法完成任务。
AtomicInteger atomicInteger = new AtomicInteger(5);
List<Future<Integer>> futures = new ArrayList<>(); //存储结果
for (int i = 0; i < 10; i++) {
Future<Integer> submit = completionService.submit(() -> {
int n = atomicInteger.getAndIncrement();
int h = 0;
for (int j = n * 10; j < n * 10 + n; j++) {
h += j;
TimeUnit.SECONDS.sleep(1); //暂停线程1s
}
return h;
});
futures.add(submit);
}
现在执行下其他的业务操作。
然后设置一些调用其他接口超时的时间,避免过长等待并开始获取下调用的结果。
Set<AjaxResult> flags = new HashSet<>();
List<AjaxResult> FAILS =new LinkedList<>();
long startTime = System.currentTimeMillis();
long timeout = 1000 * 10;
while (flags.size()+FAILS.size()<futures.size()) {
for (Future<Integer> o : futures) {
if (System.currentTimeMillis() - startTime > timeout ){// 如果超时采取一定措施,或者返回一个失败。
FAILS.add(new AjaxResult("fail",0));
if(flags.size()+FAILS.size()>=futures.size()){
break;
}
continue;
}
if (o.isDone()) {
flags.add(new AjaxResult("success", o.get()));
}
}
}
long endTime = System.currentTimeMillis();
这里将结果分失败和成功进行存储。并记录处理的时间
接下来看下最后输出结果
System.out.println("执行结束");
System.out.println("耗时" + (endTime - startTime));
System.out.println("结果" + flags.toString());
System.out.println("失败" + FAILS.toString());
System.exit(0);
本方法纯属瞎玩,仅供参考。
下面是全部的代码
public class InitConfig {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService threadPool = new ThreadPoolExecutor(
10,
10,
0,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadPoolExecutor.AbortPolicy());
CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPool);
AtomicInteger atomicInteger = new AtomicInteger(5);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<Integer> submit = completionService.submit(() -> {
int n = atomicInteger.getAndIncrement();
int h = 0;
for (int j = n * 10; j < n * 10 + n; j++) {
h += j;
TimeUnit.SECONDS.sleep(1); //暂停线程1s
}
return h;
});
futures.add(submit);
}
Set<AjaxResult> flags = new HashSet<>();
List<AjaxResult> FAILS =new LinkedList<>();
long startTime = System.currentTimeMillis();
long timeout = 1000 * 10;
while (flags.size()+FAILS.size()<futures.size()) {
for (Future<Integer> o : futures) {
if (System.currentTimeMillis() - startTime > timeout ){
FAILS.add(new AjaxResult("fail",0));
if(flags.size()+FAILS.size()>=futures.size()){
break;
}
continue;
}
if (o.isDone()) {
flags.add(new AjaxResult("success", o.get()));
}
}
}
long endTime = System.currentTimeMillis();
System.out.println("执行结束");
System.out.println("耗时" + (endTime - startTime));
System.out.println("结果" + flags.toString());
System.out.println("失败" + FAILS.toString());
System.exit(0);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode
static class AjaxResult {
private String ret;
private Integer data;
}
}