使用 JAVA 并行流时,是否可以为每个线程传递资源



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

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

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

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

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

我希望我清楚,提前感谢那些花时间回答我问题的人!

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

请参阅此小片段:

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]

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

最新更新