略坑的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方法未完成之前,操作就终止了,立即释放该线程持有的所有资源,可是操作只进行了一部分,就造成了逻辑上的不连贯。






目录
相关文章
|
5月前
|
Java 编译器 UED
Thread.sleep()总结
Thread.sleep()总结
|
6月前
|
监控 算法 Unix
Thread.sleep(0) 到底有什么用
Thread.sleep(0) 到底有什么用
54 1
Thread
Thread方法
64 0
|
Java
Java线程中的run()和start()区别
Java线程中的run()和start()区别
84 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 调度 C++
你真的了解Thread.sleep(0)吗?以及Thread.sleep(1) vs Thread.sleep(0)
你真的了解Thread.sleep(0)吗?以及Thread.sleep(1) vs Thread.sleep(0)
start
start
108 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
207 0
|
Java 程序员 调度
Thread State 详解
前言 文本已收录至我的GitHub仓库,欢迎Star:github.com/bin39232820… 种一棵树最好的时间是十年前,其次是现在
167 0
start 与 run 区别
start 与 run 区别
147 0