Java multithreading – passing data structures to threads
•
Java
The application I'm writing generates a characterlist character at some stage At this stage, I am trying to create a thread to process the ArrayList The problem is how to pass this ArrayList to the thread
Description code:
class thisApp { /* Some initial processing creates an ArrayList - aList */ Runnable proExec = new ProcessList (); //ProcessList implements Runnable Thread th = new Thread(proExec); }
Descriptive code of processlist:
public class ProcessList implements Runnable { public void run() { /* Access the ArrayList - aList - and do something upon */ } }
My question is: how do I pass and access a list in run()?
Solution
You can simply pass an alist to the constructor of processlist, which can keep the reference until it is 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 */ } }
Note: if multiple threads access the list at the same time and one or more threads modify it, all related code needs to be synchronized
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码