Return a value from asynchronous call to run method

前端 未结 3 658
情书的邮戳
情书的邮戳 2020-12-21 01:51

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. bel

3条回答
  •  死守一世寂寞
    2020-12-21 02:22

    You can use the java.util.concurrent.FutureTask if you need to adapt a Callable to a Runnable.

    public class UserQuestion implements Callable {
    
        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 futureUserAnswer = new FutureTask(userQuestion);
    Display.getDefault().asyncExec(futureUserAnswer);
    Boolean userAnswer = futureUserAnswer.get();
    

提交回复
热议问题