Return a value from asynchronous call to run method(从异步调用运行方法返回一个值)
问题描述
我有一个必须返回布尔值的方法.该方法有一个异步调用 run 方法.在运行方法中,我必须在封闭方法中设置变量.下面是我的代码.
I have a method that has to return a boolean value. The method has an asynchronous call to run method. In the run method, i have to set variable in the enclosing method. below is my code.
private boolean isTrue() {
boolean userAnswer;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
userAnswer = MessageDialog.openQuestion(new Shell(), "some message", "some question?");
}
});
return userAnswer;
}
这段代码给出了错误——userAnswer"必须是最终的,如果我把它变成最终的,我就不能给它赋值.请提出一种处理这种情况的方法.
This code gives error -- "userAnswer" has to be final, and if i make it final i cant assign a value to it. Please suggest a way to handle this scenario.
推荐答案
如果需要适配一个Callable
到一个 java.util.concurrent.FutureTask
;Runnable
.
public class UserQuestion implements Callable<Boolean> {
private String message;
private String question;
public UserQuestion(String message, String question) {
this.message = message;
this.question = question;
}
public Boolean call() throws Exception {
boolean userAnswer = MessageDialog.openQuestion(new Shell(),
message, question);
return Boolean.valueOf(userAnswer);
}
}
UserQuestion userQuestion = new UserQuestion("some message", "some question?");
FutureTask<Boolean> futureUserAnswer = new FutureTask<Boolean>(userQuestion);
Display.getDefault().asyncExec(futureUserAnswer);
Boolean userAnswer = futureUserAnswer.get();
这篇关于从异步调用运行方法返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从异步调用运行方法返回一个值


基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01