che*_*123 3 java multithreading
我正在编写的应用程序在某个阶段生成一个CharacterList字符.在这个阶段,我正在尝试创建一个线程来处理这个ArrayList.问题是如何将此ArrayList传递给线程
描述代码:
class thisApp {
/* Some initial processing creates an ArrayList - aList */
Runnable proExec = new ProcessList (); //ProcessList implements Runnable
Thread th = new Thread(proExec);
}
Run Code Online (Sandbox Code Playgroud)
ProcessList的描述性代码:
public class ProcessList implements Runnable {
public void run() {
/* Access the ArrayList - aList - and do something upon */
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何在run()中传递和访问aList?
你可以简单地传递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 */
}
}
Run Code Online (Sandbox Code Playgroud)
NB如果aList多个线程同时访问,一个或多个线程修改它,则需要所有相关代码synchronized.
| 归档时间: |
|
| 查看次数: |
2955 次 |
| 最近记录: |