1 回答
TA贡献1847条经验 获得超11个赞
您可以从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]
虽然这不是确定性的,例如每次迭代都可能导致不同的打印结果
添加回答
举报