如何给每个线程自己的一些数据副本

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

yeluogui1236 回答:如何给每个线程自己的一些数据副本

那么你能做什么:

  1. 使用arrayList作为类字段,创建您自己的扩展Thread的类
  2. 向构造函数添加对象参数
  3. 在新的构造函数中,基于传递的对象填充arrayList

    class MyThread extends Thread {
    
      private List<Location> locations;
    
      public MyThread(Object o) {
         locations = .... // do somth to convert object to arraylist
      }
    }
    
,

Ehrebeco,我想使用清单的两个深层副本。一个用于循环,另一个在线程内。希望这会有所帮助。

Srikanth Kondaveti,敬上

本文链接:https://www.f2er.com/3139883.html

大家都在问