What is the difference between ExecutorService.submit and ExecutorService.execute in this code in Java?

前端 未结 8 1409
你的背包
你的背包 2021-01-30 00:05

I am learning to use ExectorService to pool threads and send out tasks. I have a simple program below

import java.util.concurrent.Execu         


        
8条回答
  •  萌比男神i
    2021-01-30 00:36

    As you see from the JavaDoc execute(Runnable) does not return anything.

    However, submit(Callable) returns a Future object which allows a way for you to programatically cancel the running thread later as well as get the T that is returned when the Callable completes. See JavaDoc of Future for more details

    Future future = executor.submit(longRunningJob);
    ...
    //long running job is taking too long
    future.cancel(true);
    

    Moreover, if future.get() == null and doesn't throw any exception then Runnable executed successfully

提交回复
热议问题