I have an ArrayList of 10 elements. I initiate a threadpool of size 10 and call execute with an element passed into each thread. Each thread does some processing with that element as input and outputs the result. The problem is, the output sometimes has processing results of only 7 elements sometimes and 8 sometimes with a few duplicates and 9 sometimes. I am not sure why I do not have the processing results of exactly 10 elements. Here's my code snippet.
ExecutorService exeSvc =
Executors.newFixedThreadPool(10)
for (Object element: arlList)//arlList is the arraylist of
size-10
{
exeSvc.execute({->myRunnable element});
}
What am I doing wrong?
groovy...
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
ExecutorService exeSvc = Executors.newFixedThreadPool(5)
for (int element=0;element<9;element++) {
int elementCopy = element
exeSvc.execute({->
Thread.sleep(567);
println "${Thread.currentThread()} element = $element elementCopy = $elementCopy";
});
}
println "All Started"
exeSvc.shutdown()
exeSvc.awaitTermination(10, TimeUnit.SECONDS)
println "All Finished"
outputs
All Started
Thread[pool-12-thread-1,5,main] element = 9 elementCopy = 0
Thread[pool-12-thread-2,5,main] element = 9 elementCopy = 1
Thread[pool-12-thread-3,5,main] element = 9 elementCopy = 2
Thread[pool-12-thread-4,5,main] element = 9 elementCopy = 3
Thread[pool-12-thread-5,5,main] element = 9 elementCopy = 4
Thread[pool-12-thread-1,5,main] element = 9 elementCopy = 5
Thread[pool-12-thread-2,5,main] element = 9 elementCopy = 6
Thread[pool-12-thread-3,5,main] element = 9 elementCopy = 7
Thread[pool-12-thread-4,5,main] element = 9 elementCopy = 8
All Finished
as you can see in my case the for
loop finished before threads started and all of them has element
value 9 and elementCopy
is different
That's because main thread
finishes erlier than ExecutorService
.
To force Main thread
to wait for ExecutorService
to finish processing, use this:
exeSvc.awaitTermination(5, TimeUnit.SECONDS); //this will 5 second to finish all tasks
exeSvc.shutdown();
Execution time for each element is not the same. So, at the end of process, shutting down thread is required. You can use,
if ( check_whether_operation_is_done ) {
Logger.info( "Process shutdown" );
exeSvc.shutdownNow();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.