我很难理解如何通过两个线程同步ArrayList。基本上,我想要一个线程将对象附加到列表中,另一个线程同时从列表中读取对象。通过两个线程同步ArrayList
下面是部署线程类:
public class Main {
public static ArrayList<Good> goodList = new ArrayList();
public static void main(String[] args) {
Thread thread1 = new Thread(new GoodCreator());
Thread thread2 = new Thread(new WeightCounter());
thread1.start();
thread2.start();
}
}
随后两分Runnable接口的类:
这一个读取文本文件的两个值的线,并追加新的对象。
public class GoodCreator implements Runnable{
private ArrayList<Good> goodList = Main.goodList;
private static Scanner scan;
@Override
public void run() {
System.out.println("Thread 1 started");
int objCount = 0;
try {
scan = new Scanner(new File(System.getProperty("user.home") + "//Goods.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
e.printStackTrace();
}
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] words = line.split("\\s+");
synchronized(goodList){
goodList.add(new Good(Integer.parseInt(words[0]), Integer.parseInt(words[1])));
objCount++;
}
if(objCount % 200 == 0) System.out.println("created " + objCount + " objects");
}
}
}
这遍历arraylist和应该总结其中一个领域。
public class WeightCounter implements Runnable{
private ArrayList<Good> goodList = Main.goodList;
@Override
public void run() {
System.out.println("Thread 2 started");
int weightSum = 0;
synchronized(goodList){
for(Good g : goodList){
weightSum += g.getWeight();
}
}
System.out.println(weightSum);
}
}
无论输入,weightSum永远不会被递增,并保持0
Thread 1 started
Thread 2 started
0
任何帮助深表感谢
您可以使用'ArrayBlockingQueue'代替。链接:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html – user2004685
您必须使用ArrayLists吗?来自并发库的队列怎么样? – KevinO
这不是一个可重现的例子... –