So let’s say I have an iterator it that returns something of class CustomClass. The iterator has “many” CustomClass to go over. More over, let’s say that a user inputs something that makes my program decide only 5 threads can be running at any moment by my program.
In a way, something like this is expected to happen:
for(int i = 0; i < 5 && it.hasNext(); i++) {
new Thread(it.next()).start();
}
Now, again only five are allowed and there are many more elements in the iterator. But after one thread is done with its run(), I want it to call it.next() and create a new thread. BUT the problem is that it is not defined in this thread. CustomClass doesn’t even have a next() method of any kind. How would I make this work out so that each thread can “access” the iterator efficiently?
Take a look at the executors and thread pools section in the Java tutorials. The basic idea is to queue your work, and when a thread ‘becomes available’ it will pick up the next piece of work and start executing it.