This is a simplification of my code:
for(int i = 0; i < 500; i++) {
someMethod(i);
}
someMethod() takes a long time to execute, so I want to use multithreading to break up the for-loop into 5 intervals of 100:
for(int i = 0; i < 100; i++) {
someMethod(i);
}
for(int i = 100; i < 200; i++) {
someMethod(i);
}
...
for(int i = 400; i < 500; i++) {
someMethod(i);
}
so I can execute someMethod() concurrently for different i.
How do I use multithreading to accomplish this?
Please help! Thanks!
It is recommended to use the great
ExecutorServicecode for situations like this. What you do is submit all of your tasks (0 to 499) into the thread pool and they will be run concurrently by the 5 threads in the pool.Something like the following: