Java multi threading - Passing a data-structure to the thread
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 processin开发者_开发技巧g 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<Character> aList;
public ProcessList(ArrayList<Character> 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
.
Add an argument to the ProcessList
constructor.
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());
}
}
You'll have to be careful about concurrent access to the list if any other threads have access to it.
You could make the List final, but it's better to pass it in to your Runnable object.
public class ProcessList implements Runnable {
List<Character> list;
public ProcessList(List<Character> list){
this.list = list;
}
public void run() {
this.list.size();
}
}
精彩评论