java多程序并行运行,如何使用多个线程并行运行以执行非常繁重的任务

I need to execute a task which includes four steps.

Each step relies on the result of previous one. Executing all steps in one thread needs long time.

I want to use four threads and each one performs one step and use a buffer between neighboring two steps to store the result of the previous step.

I am developing on Android platform using Java.

Can anybody give me an example?

Thanks a lot.

YL

解决方案

I was curious, how the (non magically parallel) code would look like using reactive streams in java9. Turned out, the Java9 infrastructure is fragmentary and to be used with caution. So I chose to base the example on JavaRx, providing "Flows". There's an android extension available for that.

I put it in perspective with Streams, parallelStreams and sequential flows.

public class FlowStream {

@Test

public void flowStream() {

int items = 10;

List source = IntStream.range(0, items - 1).boxed().collect(Collectors.toList());

print("\nstream");

source.stream().map(this::exp).map(this::exp).forEach(i -> print("streamed %d", i));

print("\nparallelStream");

source.parallelStream().map(this::exp).map(this::exp).forEach(i -> print("streamed %d parallel", i));

print("\nflow");

Flowable.range(0, items)

.map(this::exp)

.map(this::exp)

.forEach(i -> print("flowed %d", i));

print("\nparallel flow");

Flowable.range(0, items)

.flatMap(v ->

Flowable.just(v)

.subscribeOn(Schedulers.computation())

.map(this::exp)

)

.flatMap(v ->

Flowable.just(v)

.subscribeOn(Schedulers.computation())

.map(this::exp)

).forEach(i -> print("flowed parallel %d", i));

await(5000);

}

private Integer exp(Integer i) {

print("making %d more expensive", i);

await(Math.round(10f / (Math.abs(i) + 1)) * 50);

return i;

}

private void await(int i) {

try {

Thread.sleep(i);

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

}

private void print(String pattern, Object... values) {

System.out.println(String.format(pattern, values));

}

}

io.reactivex.rxjava2

rxjava

2.2.13

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值