我有一个必须返回布尔值的方法.该方法有一个异步调用 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();
这篇关于从异步调用运行方法返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!