在许多情况下,线程 A 需要一个必须在线程 B 上计算的值。(最常见的是,B == EDT。)考虑以下示例:
String host;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
host = JOptionPane.showInputDialog("Enter host name: ");
}
});
openConnection(host);
当然,这不能编译,因为匿名内部类不允许写入host
。让它发挥作用的最简单、最干净的方法是什么?我在下面列出了我所知道的方法。
No:
Use a Future<T>并且可能Callable<T> and an ExecutorService. A Future
基本上是您想要的精确编程表达:对未来答案的承诺,以及阻止直到答案可用的能力。 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;
}
对于您的具体情况,您可能可以构建摇摆工人它实现了Future
。不要重复,请看一下这个那么问题.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)