我想用一些字符串創建一個非常簡單的回調函數。 IDE的代碼意義是呻吟聲異常未經檢查的調用。任何人都可以爲我解決這個問題嗎?這個想法最後是打包網絡調用,以便返回承諾的結果,並根據需要添加其他功能。Callback with CompletableFuture
import java.util.concurrent.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class FuturesTest {
public static void main(String[] args) throws Exception {
new FuturesTest().go();
}
private void go() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(new MakesANetworkCall())
.whenComplete(new BiConsumer<String, String>() {
@Override
public void accept(String result, String s) {
System.out.println(result.toString());
}
})
.exceptionally(new Function<Exception, Exception>() {
@Override
public Exception apply(Exception e) {
e.printStackTrace();
return e;
}
}
).thenApplyAsync(new Function<String, String>() {
@Override
public String apply(String o) {
System.out.println("Last action of all!");
return null;
}
});
System.out.println("Main thread will sleep");
Thread.sleep(2500);
System.out.println("Program over");
}
class MakesANetworkCall implements Supplier {
@Override
public String get() {
try {
System.out.println("Ground control to Major Tom");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// int i = 2/0;
return new String("Major Tom reporting!");
}
}
}
:修正了對
class MakesANetworkCall implements Supplier<String> {
和解決所有的問題隨之而來,你會得到?你爲什麼不使用lambda表達式? – Holger你想給''異常()'做什麼? – thecoop
*編輯*更改爲靜態,謝謝指出,Holger。 –