在正常使用线程时,我们关闭一个线程可以调用线程的stop()方法可以看到,方法上含有注解@Deprecated。
@Deprecated
public final void stop() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
checkAccess();
if (this != Thread.currentThread()) {
security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
}
}
// A zero status value corresponds to "NEW", it can't change to
// not-NEW because we hold the lock.
if (threadStatus != 0) {
resume(); // Wake up thread if it was suspended; no-op otherwise
}
// The VM can handle all thread states
stop0(new ThreadDeath());
}
通过注释,官方并不推荐使用stop方法。
因为stop()方法太粗暴了,一旦调用了stop(),就会直接停掉线程,但是调用的时候根本不知道线程刚刚在做什么,任务做到哪一步了,这是很危险的。同时,stop()会释放线程占用的synchronized锁,但是不会自动释放ReentrantLock锁,这也是不建议用stop()的一个因素。
官方推荐我们使用interrupt()方法来中断一个线程。可结合自定义变量,来中断一个线程的运行。
在线程池中,也是调用interrupt()方法来中断一个线程的。
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}