有没有这样一种办法
- 让两个或多个任务并行执行
- 谁先执行完, 获取结果, 判断结果是否符合要求
- 如果不符合, 等待下一个, 直到某一个异步任务结果符合要求时, 响应结果
有没有这样一种办法
没必要使用CompletableFuture
public static void main(String[] args) {
int taskCount = 3;
List<String> dataObj = new ArrayList<>();
Callback<String> callback = new CallbackImpl(dataObj, Thread.currentThread(), taskCount);
ExecutorService executorService = new ThreadPoolExecutor(1, 1, 100, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
for (int i = 0; i < taskCount; i++) {
executorService.execute(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
callback.callback("result");
});
}
LockSupport.park();
handleResult(dataObj);
executorService.shutdown();
}
Callback 如下:
class CallbackImpl implements Callback<String> {
private final List<String> list;
private final Thread thread;
private final int taskCount;
private final AtomicInteger callTimes = new AtomicInteger(0);
private final AtomicBoolean atomicBoolean=new AtomicBoolean(false);
public CallbackImpl(List<String> list, Thread thread, int taskCount) {
this.list = list;
this.taskCount = taskCount;
this.thread = thread;
}
@Override
public void callback(String s) {
if ("result".equals(s)&& !atomicBoolean.get()) {
System.out.println(s);
list.add(s);
atomicBoolean.set(true);
LockSupport.unpark(thread);
} else if(!atomicBoolean.get()) {
System.out.println(s);
if (callTimes.incrementAndGet() == taskCount) {
LockSupport.unpark(thread);
}
}
}
}
8 回答6.4k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
2 回答3.2k 阅读
2 回答3.9k 阅读
1 回答2.2k 阅读✓ 已解决
3 回答1.6k 阅读✓ 已解决
anyOf方法
理解错了。不好意思,再写一个demo