目前,我的代码正在使用相同的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
?