从异步调用返回值以运行方法 [英] Return a value from asynchronous call to run method

查看:73
本文介绍了从异步调用返回值以运行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个必须返回布尔值的方法。该方法具有异步调用以运行方法。在运行方法中,我必须在封闭方法中设置变量。

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.

推荐答案

您可以使用 java.util.concurrent。如果您需要将 Callable< V> 调整为 Runnable ,则可以使用FutureTask< V>

You can use the java.util.concurrent.FutureTask<V> if you need to adapt a Callable<V> to a 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();

这篇关于从异步调用返回值以运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆