Return a value from asynchronous call to run method

前端 未结 3 639
情书的邮戳
情书的邮戳 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:15

    You can maybe take a look at the Future Interface:

    A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future and return null as a result of the underlying task.

    0 讨论(0)
  • 2020-12-21 02:18

    There'are a lot of patterns to accomplish this. Maybe the easiest use some sort of callback function, for example:

    interface Callback {
        void onSuccess(boolean value);
    }
    
    private boolean isTrue(final Callback callback) {
    Display.getDefault().asyncExec(new Runnable() {
        public void run() {
            boolean userAnswer = MessageDialog.openQuestion(new Shell(), "some message", "some question?");
            callback.onSuccess(userAnswer);   
        }
    });
    

    }

    And invoke method like this:

    isTrue(new Callback() {
                @Override
                public void onSuccess(boolean value) {
                    // do some stuff
                }
            });
    
    0 讨论(0)
  • 2020-12-21 02:22

    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();
    
    0 讨论(0)
提交回复
热议问题