java 并行化_在Java中并行化任务的最简单方法是什么?

小编典典

特别是这样的事情:

ExecutorService EXEC = Executors.newCachedThreadPool();

List> tasks = new ArrayList>();

for (final Object object: objects) {

Callable c = new Callable() {

@Override

public Result call() throws Exception {

return compute(object);

}

};

tasks.add(c);

}

List> results = EXEC.invokeAll(tasks);

请注意,newCachedThreadPool如果objects列表很大,使用可能会很糟糕。缓存的线程池可以为每个任务创建一个线程!您可能想newFixedThreadPool(n)在n合理的地方使用(例如,假设compute()CPU受限制,则具有的内核数)。

这是实际运行的完整代码:

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class ExecutorServiceExample {

private static final Random PRNG = new Random();

private static class Result {

private final int wait;

public Result(int code) {

this.wait = code;

}

}

public static Result compute(Object obj) throws InterruptedException {

int wait = PRNG.nextInt(3000);

Thread.sleep(wait);

return new Result(wait);

}

public static void main(String[] args) throws InterruptedException,

ExecutionException {

List objects = new ArrayList();

for (int i = 0; i < 100; i++) {

objects.add(new Object());

}

List> tasks = new ArrayList>();

for (final Object object : objects) {

Callable c = new Callable() {

@Override

public Result call() throws Exception {

return compute(object);

}

};

tasks.add(c);

}

ExecutorService exec = Executors.newCachedThreadPool();

// some other exectuors you could try to see the different behaviours

// ExecutorService exec = Executors.newFixedThreadPool(3);

// ExecutorService exec = Executors.newSingleThreadExecutor();

try {

long start = System.currentTimeMillis();

List> results = exec.invokeAll(tasks);

int sum = 0;

for (Future fr : results) {

sum += fr.get().wait;

System.out.println(String.format("Task waited %d ms",

fr.get().wait));

}

long elapsed = System.currentTimeMillis() - start;

System.out.println(String.format("Elapsed time: %d ms", elapsed));

System.out.println(String.format("... but compute tasks waited for total of %d ms; speed-up of %.2fx", sum, sum / (elapsed * 1d)));

} finally {

exec.shutdown();

}

}

}

2020-09-23

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值