What's the correct way to create and use threads in a loop?
If I want to process a million items I'll create a loop to do that. So, for efficiency's sake I'll make it multi-threaded and allocate each item to a thread. Let's say I create five threads to handle this. How do I allocate the work to the threads?
What if one thread has a smaller item to process so then it's free to process another – how can I allocate the next item in the loop to that thread?
Do I create the threads outside of the loop and then use them within?
Here's an example I'm working on – it's missing the creation of object to work with and only uses two threads, but I think people here are smart enough to know what I mean :)
public class App
{
public static void main( String[] args )
{
App a = new App();
a.doTest();
}
private void doTest() {
Count c = new Count(21);
Count c2 = new Count(7);
Thread t = new Thread(c);
Thread t2 = new Thread(c2);
t.start();
t2.start();
for (int f = 0; f < 10; f++) {
//here - how do I select which thread to send the work to?
// ?????.processThis(nextObject); //how do I send this to the right thread (one that is idle or has least work?)
}
}
public class Count implements Runnable {
private int count;
public void processThis(Object someItemToProcess) {
//here I'll set the object to process and call the method to process it
}
public Count(int count) {
this.count = count;
}
@Override
public void run() {
//for illustration purposes
// for (int i = 1; i < count; i++) {
// System.out.println("Thread " + Thread.currentThread().getId() + " Count = " + i);
// }
}
}
}