简单地创建Threads来并行执行一些任务并将每个任务分配给ThreadPool是非常困难的.
ExecutorService也看起来非常简单和高效地使用,所以我想知道为什么我们不会一直使用它.
这只是一个比其他方式更快执行工作的方式吗?
这里有两个非常简单的例子来显示两种方式之间的区别:
使用执行器服务:Hello World(任务)
static class HelloTask implements Runnable { String msg; public HelloTask(String msg) { this.msg = msg; } public void run() { long id = Thread.currentThread().getId(); System.out.println(msg + " from thread:" + id); } }
使用执行器服务:Hello World(创建执行者,提交)
static class HelloTask { public static void main(String[] args){ int ntasks = 1000; ExecutorService exs = Executors.newFixedThreadPool(4); for (int i=0; i<ntasks; i++) { HelloTask t = new HelloTask("Hello from task " + i); exs.submit(t); } exs.shutdown();}}
下面显示了一个类似的例子,但是扩展了Callable界面,你能告诉我两者之间的区别,在哪种情况下应该使用一个特定的而不是另一个?
使用执行器服务:计数器(任务)
static class HelloTaskRet implements Callable<Long> { String msg; public HelloTaskRet(String msg) { this.msg = msg; } public Long call() { long tid = Thread.currentThread().getId(); System.out.println(msg + " from thread:" + tid); return tid; } }
使用执行器服务:(创建,提交)
static class HelloTaskRet { public static void main(String[] args){ int ntasks = 1000; ExecutorService exs = Executors.newFixedThreadPool(4); Future<Long>[] futures = (Future<Long>[]) new Future[ntasks]; for (int i=0; i<ntasks; i++) { HelloTaskRet t = new HelloTaskRet("Hello from task " + i); futures[i] = exs.submit(t); } exs.shutdown(); }}
解决方法
ExecutorService对于随机生成线程的优点在于它可预测地运行,并避免了线程创建的开销,这在JVM上比较大(例如,它需要为每个线程预留内存).通过可预测性,至少对于fixedThreadPool,我的意思是你知道并发线程的最大数量,你知道什么时候和如何创建它们(所以你的JVM不会在突然出现的峰值时爆发).
By Vince Emigh:@H_403_36@
ExecutorService
also supportscachedThreadPool
,which doesn’t have a
max. The main reason people choose to useExecutorService
is to
prevent the overhead of creating multiple threads (by using worker
threads@H_403_36@). It’s mostly used in cases where many small tasks need to be
executed on a separate thread. Also,don’t forget about
singleThreadExecutor
.
现在,关于Runnable vs Callable的主题,从你的例子很容易看到. Callable可以返回最终将由实际值填充的值持有者(Future). Runnables无法返回任何东西.
By Vince Emigh:@H_403_36@
Runnable
also cannot throw exceptions,whileCallable
can.