Jayesh A Lalwani wrote:Your problem is a good candidate for java.util.concurrent.ThreadPoolExecutor. The ThreadPoolExecutor contains a thread pool and a queue. You create instances of class that implement Callable and add it to the queue. All the threads wait for callable objects to appear on the queue. When an object appears, one thread pops it out, executes it and then goes back to waiting. You can set up a executor to have a pool of 5-10 threads, and put 100 objects in the queue, and they will execute them one by one. When you submit a task to the queue, the execute returns a Future object. The Future object encapsulates the result of the task. It provides methods that allow your main thread to check if the task is done and also to get the result of the task
So, in your case, you need to decide how you want to break up your processing into tasks. In both methods you have 2 for loops. Do you want to have a task for each iteration of outer loop, or have a task per iteration of the inner loop. More tasks mean smaller tasks, and that means you can have better progress tracking (if you need in the future). However, more tasks also means that you will have to do some sort of processing after tasks are complete to merge the results. so depending on how much work it is to merge the results, you might to have bigger tasks.
I would split generateRandomNumbers to have a task per iteration of inner loop. Since, all you do is add the result to a list. I would split checkIntervals to have a task per iteration of outerloop, since the inner loop counts the number of hits.
Henry Wong wrote:
4. Threads is only useful when there are resources to run the threads. Lots of threads running on lots of cores is the best case. If you are running on a single core processor box, then you have lots of threads trying to share the one available core ... and again, the multithreaded version can take longer to run than the single threaded version.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |