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]
雖然這不是確定性的,例如每次迭代都可能導致不同的打印結果
添加回答
舉報