我有下面的代码,其中执行器类型为 ExecutorService:
Runnable worker = new MyRunnable(x, y, p);
executor.execute(worker);
当一个数字打印 p 次时,我希望所有线程的执行都干净地终止,而不用等待其他线程完成它们的工作。 我该怎么做?
最佳答案
您不能完全终止线程,就像在 MS DOS 时代您不能完全终止程序一样。原因是在线程级别没有等效的进程间隔离,它们都共享相同的地址空间和其他资源。
你唯一的选择是显式地实现一个基于线程中断的合作协议(protocol),这将使线程退出他们正在做的事情自己并结束。
关于java - 在 Java 中 : how can i terminate execution of all threads without waiting for them to finish their jobs using ExecutorService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29349669/