Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

java - Return a value from asynchronous call to run method

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;
}   

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...