微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – ExecutorService与休闲主题Spawner

我有一个关于ExecutorService如何在 Java中工作的基本问题.

简单地创建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:
ExecutorService also supports cachedThreadPool,which doesn’t have a
max. The main reason people choose to use ExecutorService is to
prevent the overhead of creating multiple threads (by using worker
threads
). 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:
Runnable also cannot throw exceptions,while Callable can.

原文地址:https://www.jb51.cc/java/124779.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐