Can I use Callable threads without ExecutorService?

后端 未结 4 1851
花落未央
花落未央 2021-02-02 11:00

Can I use Callable threads without ExecutorService? We can use instances of Runnable and subclasses of Thread without ExecutorService and this code works normally. But this code

4条回答
  •  有刺的猬
    2021-02-02 11:46

    Yes you can use the call() method of a Callable or the run() method of a Runnable from your own thread directly. However this should be your last resort in special circumstances (for example integrating legacy code or unit tests). Scanners might detect this and alert you about a possible architectural problem, so it is better to not do it.

    You could also use your own ExecutorService (or use Guava's MoreExecutors.sameThreadExecutor()) which does basically the calling in the invoking thread. This will isolate your "unclean" usage of the interface to this Executor and allow it to use a different Executor whenever you want.

    BTW: be careful, when you inherit from Thread, you should never use it without start/stop as that might lead to a leak. This is one of the reasons why bug scanners alert on calling run() methods directly.

提交回复
热议问题