【发布时间】:2019-11-08 06:24:52
【问题描述】:
目前我的代码使用相同的ArrayList 来决定将每个对象移动到哪里。但我想给每个线程自己的ArrayList,并让每个线程根据它通过的object 填充自己。
我尝试使用synchronize 填充ArrayList 的方法,但这并不能解决我的问题。
for(Object o : s.objects) {
new Thread(() -> {
ArrayList<Location> locations = new ArrayList<Location>();
locations = s.getLocation(o.curLoc(), o.moves);
location nextLoc;
nextLoc = o.chooseBestLoc(locations);
o.setLocation(nextLoc);
}.start();
}
目前我认为这应该为每个线程创建一个新的ArrayList,但是我的对象移动的行为不正确。他们正在移动到看似随机的位置。
我如何给每个线程自己的ArrayList?或者让他们不能共享相同的ArrayList?
【问题讨论】:
-
locations = s.getLocation(o.curLoc(), o.moves);替换locations的值,所以在ArrayList<Location> locations = new ArrayList<Location>()中完成的初始化被丢弃 .删除初始化,因为它是资源的浪费。然后要么修复getLocation()方法以返回一个新列表,要么复制返回的列表:locations = new ArrayList<>(s.getLocation(o.curLoc(), o.moves));
标签: java multithreading arraylist state