在Java Lambda布尔方法中获取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;
}

但是,第一种方法不需要以这种方式将任务提交到线程池:

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();
}

第二种方式,通过这种方式,该方法将立即返回一个Future,再次您需要调用future#get哪个是块才能得到结果。

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。

你必须返回es.submit的结果,这是一个Future<Boolean>,或者你必须通过调用get()来等待Future的结果,这将阻塞。

最新更新