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
Descriptive Code:
class thisApp {
/* Some initial processing creates an ArrayList - aList */
Runnable proExec = new ProcessList (); //ProcessList implements Runnable
Thread th = new Thread(proExec);
}
Descriptive Code For ProcessList:
public class ProcessList implements Runnable {
public void run() {
/* Access the ArrayList - aList - and do something upon */
}
}
My problem is: How do I pass and access aList in run()?
解决方案
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 aList;
public ProcessList(ArrayList aList) {
this.aList = aList;
}
public void run() {
/* use this.aList */
}
}
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.