我今天发布了一个关于线程模式的question,几乎所有人都建议我查看ExecutorService.
当我查看ExecutorService时,我想我错过了一些东西.如果服务有运行或阻塞的线程,并且有人调用ExecutorService.shutdown(),会发生什么.正在运行或阻止的线程会发生什么?
ExecutorService在终止之前是否等待这些线程完成?
我问这个的原因是因为很久以前我曾经涉足Java时,他们弃用了Thread.stop(),我记得停止线程的正确方法是使用sempahores并在必要时扩展Thread:
public void run () {
while (!this.exit) {
try {
block();
//do something
} catch (InterruptedException ie) {
}
}
}
public void stop () {
this.exit = true;
if (this.thread != null) {
this.thread.interrupt();
this.thread = null;
}
}
ExecutorService如何处理正在运行的线程?
解决方法:
从ExecutorService#shutdown()
开始:
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
所以它会等待那些线程完成.
另一种选择是ExecutorService#shutdownNow()
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
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.
你只需要自己在run()里面的while循环中监听Thread#isInterrupted()
.