我正在尝试首次使用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..");
}
});
}
}