嗨,我有一個代碼來檢查代理。運行該方法時,我總是出錯。我理解的問題是最后一個false。當我使用 println 在控制臺上輸出它時,它在 false 和 true 之間也有所不同,但不會回傳正確的作為方法的回傳值。你能幫忙嗎!如果代理在線,代碼必須輸出true
final ExecutorService es = Executors.newFixedThreadPool(100);
public boolean isProxyOnline(String proxyIp, int proxyPort) {
es.submit(() -> {
try {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
URLConnection connection = new URL("http://www.google.com").openConnection(proxy);
connection.setConnectTimeout(1000);
connection.connect();
System.out.println("true");
return true;
} catch (Exception e) {
System.out.println("false");
return false;
}
});
return false;
}
uj5u.com熱心網友回復:
但是,第一種方式不需要通過這種方式將任務提交到執行緒池:
public boolean isProxyOnline(String proxyIp, int proxyPort) throws ExecutionException, InterruptedException {
Future<Boolean> submit = es.submit(() -> {
try {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
URLConnection connection = new URL("http://www.google.com").openConnection(proxy);
connection.setConnectTimeout(1000);
connection.connect();
System.out.println("true");
return true;
} catch (Exception e) {
System.out.println("false");
return false;
}
});
// block until the task you submitted to the thread pool completes execution and return a result(true or false).
return submit.get();
}
第二種方式,這種方式,方法會立即回傳 a Future,再次需要呼叫future#getwhich is block 來獲取結果。
public Future<Boolean> isProxyOnlineWithFuture(String proxyIp, int proxyPort) {
return es.submit(() -> {
try {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
URLConnection connection = new URL("http://www.google.com").openConnection(proxy);
connection.setConnectTimeout(1000);
connection.connect();
System.out.println("true");
return true;
} catch (Exception e) {
System.out.println("false");
return false;
}
});
}
該isProxyOnline方法的回傳值與您提交給執行緒池的任務的回傳值無關。當您向執行緒池提交任務時,您會得到一個Future,它反映了您的任務執行結果。
您也可以考慮使用 CompletableFuture 或 ListenableFuture: Listenablefuture vs Completablefuture。
uj5u.com熱心網友回復:
您必須回傳 的結果es.submit,即 a Future<Boolean>,或者您必須Future通過呼叫get()它來等待 的結果,這將阻塞。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355683.html
上一篇:如何定期檢查執行緒是否完成
