众所周知,Thread 类有一个 stop 方法,可以用来终止线程。当然,这个方法连同 suspend,resume 方法一起都已经被弃用了。原因是 stop 方法终止线程过于暴力,不管被 stop 的线程在干什么,一旦被 stop 它就得立刻停止执行,然后释放锁,这是非常不安全的。
那么,有没有办法,让被 stop 的线程继续执行,并且不释放锁呢?
我写了一段代码,各位可以拿去试试:
package per.lvjc.concurrent.stop;
public class CanNotStopThread extends Thread {
private static final Object monitor = new Object();
private boolean success = false;
int sum = 0;
@Override
public void run() {
synchronized (monitor) {
while (!success) {
try {
rollback();
work();
System.out.println("sum = " + sum);
success = true;
} catch (ThreadDeath threadDeath) {
//do nothing
}
}
}
}
private void rollback() {
System.out.println("rollback");
this.sum = 0;
}
/* 累加 1~100 */
private void work() {
int i