Java多线程 - 将数据结构传递给线程 [英] Java multi threading - Passing a data-structure to the thread
问题描述
我正在编写的应用程序在某个阶段生成一个CharacterList of Characters。在这个阶段,我正在尝试创建一个线程来处理这个ArrayList。问题是如何将此ArrayList传递给线程
The application, I am writing, generates an ArrayList of Characters at certain stage. At this stage, I am trying create a thread to process this ArrayList. The problem is how do I pass this ArrayList to the thread
描述性代码:
class thisApp {
/* Some initial processing creates an ArrayList - aList */
Runnable proExec = new ProcessList (); //ProcessList implements Runnable
Thread th = new Thread(proExec);
}
ProcessList的描述性代码:
Descriptive Code For ProcessList:
public class ProcessList implements Runnable {
public void run() {
/* Access the ArrayList - aList - and do something upon */
}
}
我的问题是:如何在运行中传递和访问aList( )?
My problem is: How do I pass and access aList in run()?
推荐答案
您只需将 aList
传递给 ProcessList
的构造函数,可以在需要之前保留引用:
You can simply pass aList
to the ProcessList
's constructor, which can retain the reference until it's needed:
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 */
}
}
NB 如果 aList
将由多个线程同时访问,其中一个或多个修改它的更多线程,所有相关代码都需要 synchronized
。
N.B. If aList
will be accessed concurrently by multiple threads, with one or more threads modifying it, all relevant code will need to be synchronized
.
这篇关于Java多线程 - 将数据结构传递给线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!