避免使用全局变量,同时允许访问另一个线程拥有的对象

Avoiding use of global variable while allowing access to object owned by another thread

我正在编写一个 Java 程序,该程序使用两个线程,一个用于不断迭代小部件的 ArrayList 并更新它们的状态,第二个是一个线程利用 swing 为基于小部件的状态。

我的问题是如何让实现了Runnable 接口的Painter 看到WidgetManager 拥有的widgets 数组列表?此外,这种模式本身就存在缺陷吗?我被教导要避免使用全局变量(例如在 main 中定义 WidgetList),但据我了解,无法将引用传递给 Runnable 线程,因为 运行() 方法不需要依赖注入。

main{
  WidgetManager wm;
  Painter painter;
  painter.run();
  wm.updateWidgets();
}

public class WidgetManager{
  volatile ArrayList<Widget> widgets;

  void updateWidgets(){
    while(true){
      //do some stuff
    }
  }
}

public class Painter implements Runnable{
  public void run(){
    //paint some stuff
  }
}

...the run() method requires no [arguments]

run() 方法由 interface 定义。您可以使用 implements(注意,不是 extends)接口的任何 class 实例创建您的线程。你的 class 可以有实例变量...

public class Painter implements Runnable{
  private ArrayList<Widget> widgets;
  public Painter(ArrayList<Widget> widgets) {
      this.widgets = widgets;
  }
  public void run(){
     paintSomeStuffBasedOnContentOf(widgets);
  }
}