简体   繁体   中英

in java: how can i terminate execution of all threads without waiting for them to finish their jobs using ExecutorService?

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?

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM