略坑的Thread.stop()

简介: 一,stop方法调用之后,线程的run不一定会立即结束首先来看下stop方法的代码: @Deprecated public final synchronized void stop(Throwable obj) { if (obj == null) ...


一,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方法全部结束之后,stop才会真正被调用。


二,可能会造成逻辑上的不连贯



如果run方法是个原子操作,当调用stop方法之后,run方法未完成之前,操作就终止了,立即释放该线程持有的所有资源,可是操作只进行了一部分,就造成了逻辑上的不连贯。






目录
相关文章
|
6月前
|
Java 编译器 UED
Thread.sleep()总结
Thread.sleep()总结
|
7月前
|
监控 安全 Java
在Java中如何优雅的停止一个线程?可别再用Thread.stop()了!
在Java中如何优雅的停止一个线程?可别再用Thread.stop()了!
99 2
|
7月前
|
监控 算法 Unix
Thread.sleep(0) 到底有什么用
Thread.sleep(0) 到底有什么用
66 1
|
Java 调度 C++
你真的了解Thread.sleep(0)吗?以及Thread.sleep(1) vs Thread.sleep(0)
你真的了解Thread.sleep(0)吗?以及Thread.sleep(1) vs Thread.sleep(0)
|
调度 C++
Thread.sleep(0) vs Thread.sleep(1) vs Thread.yield() vs Object.wait()
Thread.sleep(0) vs Thread.sleep(1) vs Thread.yield() vs Object.wait()
|
消息中间件 安全 Java
start
start
114 0
|
安全 Java 中间件
Thread.sleep(0)的作用
在源码中经常能看到sleep(0)的操作,今天来总结下sleep(0)的作用到底是啥
454 0
|
Java Linux
Thread start 源码揭秘
Thread start 源码揭秘 public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A ze
214 0