Design pattern to handle an asynchronous response in Java

前端 未结 5 2079
遥遥无期
遥遥无期 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:09

    First, you should not reject the first two methods you discuss. There are very good reasons people are using those techniques and you should try to learn them instead of creating new ones.

    Otherwise, you should look at java.util.concurrent:

    ExecutorService es = Executors.newFixedThreadPool(2);
    ...
    Future responseA = es.submit(responseGetter);
    Future responseB = es.submit(responseGetter);
    
    process(responseA.get(), responseB.get());
    

    where responseGetter is of type Callable (you must implement the method public Response call()).

提交回复
热议问题