我一直在尝试做一些简单的事情,比如将两个线程添加到一个数组列表中,但出于某种原因我无法让它工作。我有同步方法并使用 Collections.synchronized 列表,但它仍然显示它正在打印两个单独的数组。我编写了一个简短的程序,以便更好地理解运行两个线程来访问一个 arrayList。如果有人能够阐明我犯了什么错误,我们将不胜感激!
这是主类
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RunThreads {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
int[] numbers1 = {0, 2, 4, 6, 8};
int[] numbers2 = {1, 3, 5, 7, 9};
executor.execute(new ThreadToRun(numbers1));
executor.execute(new ThreadToRun(numbers2));
executor.shutdown();
}
}
这是 TheadToRun 类:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ThreadToRun implements Runnable {
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
private int[] array;
public ThreadToRun(int[] array) {
this.array = array;
}
public void run() {
list = adder(array);
for(int i=0; i<list.size(); i++){
System.out.print(list.get(i)+"("+i+")"); //print out the element at i and the index
} //to see if there are two arrays with the same index
}
public List<Integer> adder(int [] a){
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
for (int array : a) {
synchronized(list){
list.add(array);
}
}
return list;
}
}
在这里,您将创建两个“TheadToRun”实例,每个实例实例化一个新的列表实例(如下所述)
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
此外,在您的加法器方法中,您还执行以下操作:
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
这将再次创建一个新列表并覆盖实例中的现有列表。
可能的解决方案:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ThreadToRun implements Runnable {
List<Integer> list;
private int[] array;
public ThreadToRun(int[] array, List<Integer> list) {
this.array = array;
this.list = list;
}
public void run() {
for (int array : a) {
list.add(array);
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RunThreads {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
int[] numbers1 = {0, 2, 4, 6, 8};
int[] numbers2 = {1, 3, 5, 7, 9};
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
ThreadToRun t1 = new ThreadToRun(numbers1, list);
ThreadToRun t2 = new ThreadToRun(numbers1, list);
executor.execute(t1);
executor.execute(t2);
executor.shutdown();
// print the list out
for(int i=0; i<list.size(); i++){
System.out.print(list.get(i) + " found at location ("+i+")");
}
}
}
我是一名优秀的程序员,十分优秀!