我很難理解如何通過兩個線程同步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
這不是一個可重現的例子... –