【发布时间】:2016-08-15 03:38:30
【问题描述】:
我很难理解如何在两个线程上同步 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。链接:docs.oracle.com/javase/7/docs/api/java/util/concurrent/… -
必须使用 ArrayLists 吗?来自并发库的队列怎么样?
-
这不是一个可重复的例子......
-
@YassinHajaj 这就是并发错误很难找到的原因:它们通常是不可重现的。在这种情况下,两个线程之间存在明显的数据竞争。
标签: java multithreading arraylist