实现Runnable与扩展线程 [英] Implementing Runnable vs. extending Thread
本文介绍了实现Runnable与扩展线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么实现Runnable比从Thread类扩展更好?
Why is implementing Runnable a better option than extending from Thread class?
推荐答案
这样你解耦执行中的计算(什么)(时间和/或如何)。
This way you decouple the computation (the what) from the execution (the when and/or the how).
使用 Runnable
或 Callable
,您可以举例说明提交许多工作/计算到 Executor
,这将负责安排这些东西。以下是 ExecutorService :
With Runnable
or Callable
, you can for instance submit many work/computation to an Executor
which will take care to schedule the stuffs. Here is an excerpt form ExecutorService:
pool = Executors.newFixedThreadPool(poolSize);
...
pool.execute(new Handler(serverSocket.accept()));
...
class Handler implements Runnable {
...
}
使用 Runnable
/ Callable
为您提供更大的灵活性,直接使用Threads。
Using Runnable
/Callable
gives you more flexibility that using Threads directly.
这篇关于实现Runnable与扩展线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文