Use ExecutorCompletionService , Executor and Callable .:
Start with Callable , which calls your int function:
public class MyCallable implements Callable<Integer> { private final int i; public MyCallable(int i) { this.i = i; } public Integer call() { return Integer.valueOf(myFunction(i)); } }
Create an Executor :
private final Executor executor = Executors.newFixedThreadPool(10);
10 - the maximum number of threads to execute immediately.
Then wrap it in an ExecutorCompletionService and submit your jobs:
CompletionService<Integer> compService = new ExecutionCompletionService<Integer>(executor);
ExecutorCompletionService allows you to pull jobs out of the queue as they are completed. This is slightly different from thread pooling. Although the overall result is the same, if you want to update the user interface as threads finish, you wonβt know in which order the threads will be terminated using the connection. This last for loop could be like this:
for (int i = 0; i < jobCount; i++) { a += compService.take().get().intValue(); updateUi(a); }
And this will update the user interface when tasks are completed. Using Thread.join will not necessarily do this, as you will get the results in the order in which you call the connections, and not in the order in which the threads terminated.
Using an artist, this will also allow you to limit the number of simultaneous tasks that you are currently performing so that you do not accidentally bomb your system.
Brian source share