gpt4 book ai didi

java - 添加回调 ListenableFuture

转载 作者:行者123 更新时间:2023-12-01 22:58:27 24 4
gpt4 key购买 nike

我第一次尝试使用ListenableFutues,在使用addCallback方法时出现错误,请帮忙。

附件是代码的快照。错误是:

error: <identifier> expected
Futures.addCallback(futureRequest,new FutureCallback<T>() {
^

error: <identifier> expected
Futures.addCallback(futureRequest,new FutureCallback<T>() {
^

最佳答案

您可以像下面一样实现 ListenableFuture 回调。

    import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

public class EventDriver<T> {
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

public void prepare() {
Callable<T> task = null; // Whatever task you need to assign
ExecutorService executorService = Executors.newFixedThreadPool(10);

ListeningExecutorService service = MoreExecutors.listeningDecorator(executorService);
ListenableFuture<T> futureRequest = service.submit(task);
Futures.addCallback(futureRequest, new FutureCallback<T>() {
@Override
public void onSuccess(T result) {
logger.info("Sucess..");
}

@Override
public void onFailure(Throwable t) {
logger.info("Failure..");
}
});
}
}

关于java - 添加回调 ListenableFuture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58430522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com