一,stop方法调用之后,线程的run不一定会立即结束
首先来看下stop方法的代码:
@Deprecated
public final synchronized void stop(Throwable obj) {
if (obj == null)
throw new NullPointerException();
SecurityManager security = System.getSecurityManager();
if (security != null) {
checkAccess();
if ((this != Thread.currentThread()) ||
(!(obj instanceof ThreadDeath))) {
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(obj);
}
stop方法是一个同步方法,在执行时候,会抛出ThreadDeath异常
public class StopThreadTest {
@Test
public void stopTest() throws InterruptedException {
Thread t = new someThread();
t.start();
Thread.sleep(7);
t.stop();
}
class someThread extends Thread {
public synchronized void run() {
for (int i = 0; i < 1000000; i++) {
System.out.println("i=" + i);//一直全部打印完
}
System.out.println("打印完成!!!");
}
}
}
二,可能会造成逻辑上的不连贯
如果run方法是个原子操作,当调用stop方法之后,run方法未完成之前,操作就终止了,立即释放该线程持有的所有资源,可是操作只进行了一部分,就造成了逻辑上的不连贯。