Design pattern to handle an asynchronous response in Java

前端 未结 5 2129
遥遥无期
遥遥无期 2021-01-30 18:51

I read answers from similar Q&A

How do you create an asynchronous HTTP request in JAVA? | Asynchronous programming design pattern |
AsyncTask Android - Design P

5条回答
  •  长情又很酷
    2021-01-30 19:08

    Could CountDownLatch help you? In the main method, you call getResponse and then countDownLatch.await(). Pass a count down latch to the getResponse method and then count down once getResponse the result from getResponse is finished:

    CountDownLatch latch = new CountDownLatch(1);
    Response a = getResponse(latch);
    latch.await();
    
    latch = new CountDownLatch(1);
    Response b = getResponse(latch);
    latch.await();
    
    process(a, b);
    

    Your getResponse needs to call latch.countDown() once it's asynch parts return a result.

    e.g.:

    public Response getResponse(CountDownLatch latch) {
         someAsychBloc(final CountDownLatch latch) {
           do work
           latch.countDown();
        }
    }
    

提交回复
热议问题