如何为每个线程提供自己的某些数据副本

问题描述 投票:0回答:2

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

java multithreading arraylist state
2个回答
0
投票

所以你能做什么:

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

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

-1
投票

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

问候,Srikanth Kondaveti

© www.soinside.com 2019 - 2024. All rights reserved.