I am using executorService to excecute only one task at a time using this code
executorService=Executors.newSingleThreadExecutor();
And I am using Thread.activeCount()
to get the number of active threads, but whenever I submit a runnable task to the executorService the number of active threads is incremented by one. How is that possible?
I thought newSingleThreadExecutor()
allows executing only one task at a time. Why does the number of threads keep increasing? Shouldn't the number of threads only increase by one and not more?
Note that I am also using future
to cancel execution of all runnables before even submitting a new task and it works fine; all runnables are interrupted. However, the number of active threads keeps increasing.
Edit: This is the code that gets called whenever I press on a button (Worker
is just a class that implements runnable):
private void handle() {
executorService=Executors.newSingleThreadExecutor();
Worker worker=new Worker();
future=executorService.submit(new Worker());
}
Each time you call it it cretes a new Executor. Each single threaded executor has its own thread. If you want to do multiple jobs on that executor you call newSingleThreadedExecutor once and submit all the jobs to that executor. You do not call newSingleThreadedExecutor multiple times
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With