我有一个简单的任务: 有一个数组列表,我需要使用线程池在所有数组中找到除以 10 的数字。
这是我的代码
导入java.util.List;
可运行的实现:
public class MyRunnable implements Runnable {
private List<Integer> numbers;
private int[] arrayToFind;
public MyRunnable(List<Integer> numbers, int[] arrayToFind) {
this.numbers = numbers;
this.arrayToFind = arrayToFind;
}
private boolean isNumber(int n) {
return n % 10 == 0;
}
@Override
public void run() {
for (int i = 0; i < arrayToFind.length; i++) {
if (isNumber(arrayToFind[i]))
numbers.add(arrayToFind[i]);
}
}
}
主类:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String... args) throws InterruptedException{
int[] arr1 = new int[] {10};
int[] arr2 = new int[] {400};
int[] arr3 = new int[] {20};
int[] arr4 = new int[] {40};
List<int[]> list = new ArrayList<int[]>();
list.add(arr1);
list.add(arr2);
list.add(arr3);
list.add(arr4);
List<Integer> result = new ArrayList<Integer>();
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int[] array : list) {
executorService.execute(new MyRunnable(result, array));
}
executorService.shutdown();
System.out.println(result);
}
}
问题在于,输出有时是正确的,因为它应该是 {10, 20, 40, 400},但有时是 {},有时是 {40, 20} 等等。
你如何解释这一点?
最佳答案
默认插入列表 are not synchronized ,因此不是线程安全的。如果您想实现线程安全(这样就不会丢失数据),请将您的实例包装在 Collections.synchronizedList
中。
List<Integer> result = Collections.synchronizedList(new ArrayList<Integer>());
现在您的结果将全部显示(当然,仍然以不确定的顺序)。
关于java - 线程池的工作方式不可预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26078895/