Java多线程 - 将数据结构传递给线程

时间:2011-06-10 17:05:00

标签: java multithreading

我正在编写的应用程序在某个阶段生成一个CharacterList of Characters。在这个阶段,我正在尝试创建一个线程来处理这个ArrayList。问题是如何将此ArrayList传递给线程

描述性代码:

class thisApp {
    /* Some initial processing creates an ArrayList - aList */

    Runnable proExec = new ProcessList (); //ProcessList implements Runnable
    Thread th = new Thread(proExec);
}

ProcessList的描述性代码:

public class ProcessList implements Runnable {
    public void run() {
      /* Access the ArrayList - aList - and do something upon */
    }
}

我的问题是:如何在run()中传递和访问aList?

3 个答案:

答案 0 :(得分:6)

您可以简单地将aList传递给ProcessList的构造函数,该构造函数可以保留引用直到需要它为止:

class thisApp {
    /* Some initial processing creates an ArrayList - aList */

    Runnable proExec = new ProcessList (aList);
    Thread th = new Thread(proExec);
}

public class ProcessList implements Runnable {
    private final ArrayList<Character> aList;
    public ProcessList(ArrayList<Character> aList) {
      this.aList = aList;
    }
    public void run() {
      /* use this.aList */
    }
}

N.B。如果多个线程同时访问aList,并且有一个或多个线程修改它,则所有相关代码都需要synchronized

答案 1 :(得分:4)

ProcessList构造函数添加参数。

public class ProcessList implements Runnable
{    
    private final List<Foo> aList;

    public ProcessList(List<Foo> aList)
    {
        this.aList = aList;
    }

    public void run()
    {
      System.out.println(aList.size());
    }
}

如果任何其他线程有权访问列表,则必须小心并发访问列表。

答案 2 :(得分:2)

您可以将List设为final,但最好将其传递给Runnable对象。

public class ProcessList implements Runnable {
    List<Character> list;
    public ProcessList(List<Character> list){
    this.list = list;
    }
    public void run() {
         this.list.size();
    }
}