Executing Java callback on a new thread

后端 未结 2 536
旧时难觅i
旧时难觅i 2021-01-14 06:57

On this project, a Manager performs event queuing, and to return the result of the event a callback is used (the callback does not extend Runnable)

2条回答
  •  悲哀的现实
    2021-01-14 07:44

    I would have the thread which executes the task, also execute the call back. Instead of creating a Thread each time, I suggest you use an ExecutorService.

    public static  void submit(ExecutorService service, 
                                  Callable callable,
                                  Consumer callback) {
        service.submit(() -> {
             try {
                 callback.accept(callable.call());
             } catch (Throwable t) {
                 // log the Throwable
             }
         });
     }
    

提交回复
热议问题