【问题标题】:How to give each thread its own copy of some data如何给每个线程自己的一些数据副本
【发布时间】: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&lt;Location&gt; locations = new ArrayList&lt;Location&gt;() 中完成的初始化被丢弃 .删除初始化,因为它是资源的浪费。然后要么修复 getLocation() 方法以返回一个新列表,要么复制返回的列表:locations = new ArrayList&lt;&gt;(s.getLocation(o.curLoc(), o.moves));

标签: java multithreading arraylist state


【解决方案1】:

那么你能做什么:

  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
      }
    }
    

【讨论】:

    【解决方案2】:

    Ehrebeco,我认为使用列表的两个深层副本。一个用于循环,一个用于线程内。希望这会有所帮助。

    问候,Srikanth Kondaveti

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 2019-07-17
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多