gpt4 book ai didi

java - Java用多个线程处理一个数组

转载 作者:行者123 更新时间:2023-12-03 13:23:27 24 4
gpt4 key购买 nike

我想在程序中实现多个线程。这些多个线程应该能够处理一个单独的数组。
例如:
我有一个整数数组:

int[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
现在,多个线程应将每个项目打印到控制台,如下所示:
1 //Printed by Thread 1
2 //Printed by Thread 2
7 //Printed by Thread 1
8 //Printed by Thread 2
9 //Printed by Thread 3
4 //Printed by Thread 1
5 //Printed by Thread 2
6 //Printed by Thread 3
3 //Printed by Thread 3
10 //Printed by Thread 1
11 //Printed by Thread 2
12 //Printed by Thread 3
(结果是否随机无关紧要。)
到目前为止,我的解决方案是将数组拆分为较小的块。这是可行的,但我不太喜欢该解决方案,并且我认为这不是真正的线程安全的
    public static void main(String[] args) {

int[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

int chunk = 3;
for (int i = 0; i < integerArray.length; i += chunk) {

int finalI = i;

new Thread(() -> {
int[] splittedArray = Arrays.copyOfRange(integerArray, finalI, Math.min(integerArray.length, finalI + chunk));
for (int value : splittedArray) {
System.out.println(value);
}

}).start();
}

}

最佳答案

出于上面给出的示例中的目的,您无需拆分数组即可将部件传递给并行线程。使用并行流来处理数组的元素将为您做到这一点:

public static void main(String... args) {
int[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Arrays.stream(integerArray)
.parallel()
.forEach(x -> System.out.println(Thread.currentThread().getName() + " printed value: " + x));
}
在输出中,您可以看到ForkJoinPool-Worker-Threads将在打印您的元素。

关于java - Java用多个线程处理一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62656312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com