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 Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01