【问题标题】:Is it possible to pass ressources per thread when using JAVA parallel streams?使用 JAVA 并行流时是否可以为每个线程传递资源?
【发布时间】:2019-01-24 13:27:07
【问题描述】:

我的问题真的很简单,但我没有找到明确回答的主题......(也许我错过了......:o)。 我想知道,在使用并行流时,是否可以为每个线程提供自定义数据(每个线程不同)。

例如,我们可以想象我想知道哪个线程处理了哪个实体。

例如:我有以下集合 [0,1,2,3,4,5] 我创建并行流并使用 map 方法使正方形与每个元素相关联。 我应该有以下输出:[0,1,4,9,16,25] 但我想确定哪个线程处理了哪些实体,例如,如果我有 2 个线程:

线程 1 -> [0,1,2]

线程 2 -> [3,4,5]

我希望我很清楚,在此先感谢那些愿意花时间回答我问题的人!

【问题讨论】:

  • 为什么会想要这种信息?
  • Re, "...哪个线程处理了哪个实体..." 您假设只有一个线程“处理”每个“实体”。该假设可能不适用于非平凡的流。

标签: java multithreading parallel-processing java-stream


【解决方案1】:

使用Thread.currentThread(),您可以从当前活动的上下文中获取线程。

看到这个小sn-p:

final int[] ints = IntStream.range(0, 6)
    .parallel()
    .map(i -> {
        System.out.println("thread " + Thread.currentThread().getName() + " maps " + i + " to " + i * i);
        return i * i;
    })
    .toArray();

System.out.println("Final array " + Arrays.toString(ints));

打印如下内容:

thread main maps 5 to 25
thread ForkJoinPool.commonPool-worker-1 maps 2 to 4
thread ForkJoinPool.commonPool-worker-2 maps 3 to 9
thread ForkJoinPool.commonPool-worker-3 maps 0 to 0
thread main maps 1 to 1
thread ForkJoinPool.commonPool-worker-4 maps 4 to 16
Final array [0, 1, 4, 9, 16, 25]

虽然这不是确定性的,例如每次迭代可能会导致不同的打印结果

【讨论】:

  • 如果您使用Thread.currentThread() 的结果作为容器中对象的唯一索引,那么您几乎是在重新发明java.lang.ThreadLocal
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
相关资源
最近更新 更多