1

I have the code below, where executor is type ExecutorService:

Runnable worker = new MyRunnable(x, y, p);
                executor.execute(worker);

When a number prints p times, i want the execution of all threads to be terminated cleanly without waiting the other threads to finish their jobs. How can i do that?

c_user89
  • 53
  • 1
  • 9

2 Answers2

3

You cannot cleanly terminate threads, much like in the days of MS DOS you couldn't cleanly terminate a program. The reason is that there is no equivalent of interprocess isolation at the level of threads, they all share the same address space and other resources.

Your only option is to explicitly implement a cooperative protocol based on thread interruption which will make the threads quit what they are doing on their own and end.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

Try executor.shutdownNow() for this. But, as said in ExecutorService Javadoc,

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdownNow%28%29

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67