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

Say I have a task like:

for(Object object: objects) {

Result result = compute(objects);

list.add(result);

}

What is the easiest way to parallelize each compute() (assuming they are already parallelizable)?

I do not need an answer that matches strictly the code above, just a general answer. But if you need more info: my tasks are IO bound and this is for a Spring Web application and the tasks are going to be executed in a HTTP request.

解决方案

I would recommend taking a look at ExecutorService.

In particular, something like this:

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);

Note that using newCachedThreadPool could be bad if objects is a big list. A cached thread pool could create a thread per task! You may want to use newFixedThreadPool(n) where n is something reasonable (like the number of cores you have, assuming compute() is CPU bound).

Here's full code that actually runs:

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();

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值