Java multithreading - Passing data structure to stream

The application I'm writing generates an ArrayList of characters at a certain point. At this point I am trying to create a thread to handle this ArrayList. The problem is how to pass this ArrayList to the stream

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 the process list:

public class ProcessList implements Runnable {
    public void run() {
      /* Access the ArrayList - aList - and do something upon */
    }
}

My problem: how to pass and access aList in run ()?

+3
source share
3 answers

You can simply pass it aListto the constructor ProcessList, which can save the link 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 */
    }
}

NB If it aListwill be available simultaneously by multiple threads, with one or more threads modifying it, all relevant code should be synchronized.

+6

ProcessList.

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());
    }
}

, .

+4

You can make a final list, but it's better to pass it to your Runnable.

public class ProcessList implements Runnable {
    List<Character> list;
    public ProcessList(List<Character> list){
    this.list = list;
    }
    public void run() {
         this.list.size();
    }
}
+2
source

All Articles