I have a list that contains roughly 200K elements.
Am I able to pass the iterator for this list to multiple threads and have them iterate over the whole lot, without any of them accessing the same elements?
This is what I am thinking of at the moment.
Main:
public static void main(String[] args)
{
// Imagine this list has the 200,000 elements.
ArrayList<Integer> list = new ArrayList<Integer>();
// Get the iterator for the list.
Iterator<Integer> i = list.iterator();
// Create MyThread, passing in the iterator for the list.
MyThread threadOne = new MyThread(i);
MyThread threadTwo = new MyThread(i);
MyThread threadThree = new MyThread(i);
// Start the threads.
threadOne.start();
threadTwo.start();
threadThree.start();
}
MyThread:
public class MyThread extends Thread
{
Iterator<Integer> i;
public MyThread(Iterator<Integer> i)
{
this.i = i;
}
public void run()
{
while (this.i.hasNext()) {
Integer num = this.i.next();
// Do something with num here.
}
}
}
My desired outcome here is that each thread would process roughly 66,000 elements each, without locking up the iterator too much, and also without any of the threads accessing the same element.
Does this sound doable?
Stream
s andparallel()
seems to be the appropriate use case here. – FrissellhasNext
andnext
calls are not atomic. – Dnieper