在很多情况下,线程 A 需要一个必须在线程 B 上计算的值。(最常见的是,B == EDT。)请考虑以下示例:
String host;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
host = JOptionPane.showInputDialog("Enter host name: ");
}
});
openConnection(host);
当然,这不会编译,因为不允许匿名内部类写入host
。让它工作的最简单、最干净的方法是什么?我在下面列出了我所知道的方法。
最佳答案
否:
使用 Future<T>
可能还有 Callable<T>
和一个 ExecutorService
. Future
基本上是对您想要的内容的精确编程表达:对 future 答案的 promise ,以及在答案可用之前阻塞的能力。 Future 还会自动为您包装和呈现一整套复杂的潜在并发噩梦和复杂性,并将其呈现为几个明确定义的异常。这是一件好事,因为它迫使您处理它们,而您自己的解决方案可能永远不会揭示它们,除非出现一些异常的、难以诊断的行为。
public void askForAnAnswer() throws TimeoutException, InterruptedException, ExecutionException
{
Future<String> theAnswerF = getMeAnAnswer();
String theAnswer = theAnswerF.get();
}
public Future<String> getMeAnAnswer()
{
Future<String> promise = null;
// spin off thread/executor, whatever.
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
host = JOptionPane.showInputDialog("Enter host name: ");
}
});
// ... to wrap a Future around this.
return promise;
}
对于您的具体情况,您可能可以在 SwingWorker 上构建实现Future
.不要复制,请看一下这个 SO question .
关于java - 如何检索必须在另一个线程上计算的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3981924/