search

Home  >  Q&A  >  body text

异步编程 - 在Java中使用异步后,主方法如何返回异步中得到的值?

一个返回值为User的方法,在内部调用了异步方法(比如Rxjava,或者异步的网络请求),其内部匿名函数内才能拿到user对象,那么我的方法应该怎么return这个对象?

PHPzPHPz2766 days ago490

reply all(7)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 09:53:32

    The return value of the method is user, so this method cannot be called an asynchronous method. Unless this method returns a future, or something like a reference that can get the result later, this method can be called an asynchronous method. If you want to get the user after adjusting the method, then there is no need to place asynchronous code in the method, which is meaningless at all.

    Asynchronous return results can only be returned through callbacks.

    The synchronization method is usually like this

    public User syncGetUser() {
        User user = heavyWork();
        return user;
    }

    Since the heavyWork method may need to check the database or do a lot of calculations, the heavyWork method will take a lot of time to execute.
    If you don’t want to wait a lot of time, this is where asynchronous comes in handy.

    public Future<User> asyncGetUser() {
        Future<User> future = threadPool.submit(new Callable<User> {
            public User call() throws Exception {
                return heavyWork();
            }
        }
        
        return future;
    }

    At this point, heavyWork has been handed over to another thread to run, and a future is returned to you.
    After that, you can get the user you want through the get method of this future.

    This is the meaning and usefulness of asynchronous. The title itself is contradictory. Returning the result of asynchronous execution in a method containing asynchronous code is a contradiction.

    reply
    0
  • 阿神

    阿神2017-04-18 09:53:32

    I have not studied RxJava, but my colleagues who did Android development in the previous team said it is very useful.

    The 1st floor gave a solution using Future, but unfortunately Future is an asynchronous blocking API, that is, there is no notification callback.

    As for how to implement callbacks, this should be very basic. Just look at the observer pattern. The essence is to use the polymorphic characteristics of the interface.

    But you can use google guava, which provides an enhanced Future called ListenableFuture.

    The example on the 1st floor is quoted here and modified.

     class A implements FutureCallback{
            ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
            ListenableFuture futrue = service.submit(new Callable() {
                public User call() {
                    return heavyWork();
                }
            });
            Futures.addCallback(furtrue,this);
    
            public void onSuccess(User user) {
                //这个是回调执行的代码
            }
            public void onFailure(Throwable thrown) {
    
            }
        }

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:53:32

    The "return" of an asynchronous method occurs before the code is executed. The code has not been executed yet, how can the result be returned?

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 09:53:32

    I think it’s also okay to use callbacks

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:53:32

    Use CountDownLatch to convert asynchronous operations into synchronous operations.

    final CountDownLatch latch = new CountDownLatch(1);

    Call asynchronous methods.
    In the asynchronous callback result,
    latch.countDown();

    Then
    try {

    latch.await();
    

    } catch (InterruptedException e) {
    }

    return data;

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:53:32

    There is a thread in java that returns the Callable interface

    reply
    0
  • 阿神

    阿神2017-04-18 09:53:32

    rx.java I have never been exposed to
    but I know the methods in android, I hope it will be helpful to you.
    According to what you said, if the asynchronous return result is used in the main method, then the communication between threads must be taken into consideration
    That is, write a handler first, and write a method to receive the data, and execute the method you want to execute when the data comes in
    Then After the sub-thread is finished running, just send data to the handler.

    reply
    0
  • Cancelreply