-1

I have a method I need to call for each element in a list, then return this list to the caller in another class. I want to create a Thread for each element but am struggling to get my head around how to do this.

public List<MyList> threaded(List<Another> another) {
    List<MyList> myList= new ArrayList<>();
    Visibility visi = new Visibility();

    Thread[] threads = new Thread[another.size()];
    for (int i = 0; i < another.size(); i++) {
        visi = test(another.get(i));
        myList.add(visi);
    }
    return myList;
}

So i've defined an array of threads that matches the number of elements in another list. To use each of those threads in the loop and then return the myList after all threads have been executed is where i'm lost.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
arsenal88
  • 1,040
  • 2
  • 15
  • 32
  • Two things: first, you should not create new thread for every element. If you list has 1000 elements your application will spend more time waiting for operating system to schedule all those threads then doing actual stuff. Second, if your threads add elements to the same collection that collection must be thread-safe. So two most common options: use parallelStream or use thread pool via ExecutorService – Ivan Sep 06 '18 at 11:04

1 Answers1

4

This looks like a perfect use case for a Stream.parallelStream()

public List<MyList> threaded(List<Another> another) {
    return another.parallelStream()
                  .map(a -> test(a));
                  .collect(Collectors.toList());
}

This will call test on each Another and collect the results as a List using as many cpus as you have available (up to the number of objects you have)

Yes, you could create a Thread for each one, except this is like to be less efficient and much more complicated.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130