3

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()?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is highly unlikely that the list will be simultaneously accessed. Anyways, Thanks!
4

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.

Comments

2

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

2 Comments

"You could make the List final" - I don't get what you're saying there.
I was suggesting that if the list was in scope then by making it final you could reference it from within the threads run method without passing it in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.