`

【转】为什么不使用Thread.stop()方法

阅读更多

为什么不能使用Thread.stop()方法?

从SUN的官方文档可以得知,调用Thread.stop()方法是不安全的,这是因为当调用Thread.stop()方法时,会发生下面两件事:

1. 即刻抛出ThreadDeath异常,在线程的run()方法内,任何一点都有可能抛出ThreadDeath Error,包括在catch或finally语句中。

2. 释放该线程所持有的所有的锁

 

当线程抛出ThreadDeath异常时,会导致该线程的run()方法突然返回来达到停止该线程的目的。ThreadDetath异常可以在该线程run()方法的任意一个执行点抛出。但是,线程的stop()方法一经调用线程的run()方法就会即刻返回吗?

 

 

Java代码 复制代码 收藏代码
  1. public static void main(String[] args) {   
  2.         try {   
  3.             Thread t = new Thread() {   
  4.                 public synchronized void run() {   
  5.                     try {   
  6.                         long start=System.currentTimeMillis();   
  7.                         for (int i = 0; i < 100000; i++)   
  8.                             System.out.println("runing.." + i);   
  9.                         System.out.println((System.currentTimeMillis()-start)/1000);   
  10.                     } catch (Throwable ex) {   
  11.                         System.out.println("Caught in run: " + ex);   
  12.                         ex.printStackTrace();   
  13.                     }   
  14.                 }   
  15.             };   
  16.             t.start();   
  17.             // Give t time to get going...   
  18.             Thread.sleep(100);   
  19.             t.stop(); // EXPECT COMPILER WARNING   
  20.         } catch (Throwable t) {   
  21.             System.out.println("Caught in main: " + t);   
  22.             t.printStackTrace();   
  23.         }   
  24.   
  25.     }  
[java] view plaincopy
 
  1. public static void main(String[] args) {  
  2.         try {  
  3.             Thread t = new Thread() {  
  4.                 public synchronized void run() {  
  5.                     try {  
  6.                         long start=System.currentTimeMillis();  
  7.                         for (int i = 0; i < 100000; i++)  
  8.                             System.out.println("runing.." + i);  
  9.                         System.out.println((System.currentTimeMillis()-start)/1000);  
  10.                     } catch (Throwable ex) {  
  11.                         System.out.println("Caught in run: " + ex);  
  12.                         ex.printStackTrace();  
  13.                     }  
  14.                 }  
  15.             };  
  16.             t.start();  
  17.             // Give t time to get going...  
  18.             Thread.sleep(100);  
  19.             t.stop(); // EXPECT COMPILER WARNING  
  20.         } catch (Throwable t) {  
  21.             System.out.println("Caught in main: " + t);  
  22.             t.printStackTrace();  
  23.         }  
  24.   
  25.     }  

 

假设我们有如上一个工作线程,它的工作是数数,从1到1000000,我们的目标是在它进行数数的过程中,停止该线程的运作。如果我们按照上面的方式来调用thread.stop()方法,原则上是可以实现我们的目标的,根据SUN官方文档的解释,加上在上面的程序中,主线程只休眠了100ms,而工作线程从1数到1000000所花时间大概是4-5s,那么该工作线程应该只从1数到某个值(小于1000000),然后线程停止。 

 

但是根据运行结果来看,并非如此。

 

结果:

。。。

 

runing..99998

runing..99999

5

 

 

。。。

 

runing..99998

runing..99999

4

 

每次运行的结果都表明,工作线程并没有停止,而是每次都成功的数完数,然后正常中止,而不是由stop()方法进行终止的。这个是为什么呢?根据SUN的文档,原则上只要一调用thread.stop()方法,那么线程就会立即停止,并抛出ThreadDeath error,查看了Thread的源代码后才发现,原先Thread.stop0()方法是同步的,而我们工作线程的run()方法也是同步,那么这样会导致主线程和工作线程共同争用同一个锁(工作线程对象本身),由于工作线程在启动后就先获得了锁,所以无论如何,当主线程在调用t.stop()时,它必须要等到工作线程的run()方法执行结束后才能进行,结果导致了上述奇怪的现象。

 

把上述工作线程的run()方法的同步去掉,再进行执行,结果就如上述第一点描述的那样了

 

可能的结果:


runing..4149
runing..4150
runing..4151
runing..4152runing..4152Caught in run: java.lang.ThreadDeath

 

或者

 

runing..5245
runing..5246
runing..5247
runing..5248runing..5248Caught in run: java.lang.ThreadDeath

 

 

 

接下来是看看当调用thread.stop()时,被停止的线程会不会释放其所持有的锁,看如下代码:

 

Java代码 复制代码 收藏代码
  1. public static void main(String[] args) {   
  2.         final Object lock = new Object();   
  3.         try {   
  4.             Thread t0 = new Thread() {   
  5.                 public void run() {   
  6.                     try {   
  7.                         synchronized (lock) {   
  8.                             System.out.println("thread->" + getName()   
  9.                                     + " acquire lock.");   
  10.                             sleep(3000);// sleep for 3s   
  11.                             System.out.println("thread->" + getName()   
  12.                                     + " release lock.");   
  13.                         }   
  14.                     } catch (Throwable ex) {   
  15.                         System.out.println("Caught in run: " + ex);   
  16.                         ex.printStackTrace();   
  17.                     }   
  18.                 }   
  19.             };   
  20.   
  21.             Thread t1 = new Thread() {   
  22.                 public void run() {   
  23.                     synchronized (lock) {   
  24.                         System.out.println("thread->" + getName()   
  25.                                 + " acquire lock.");   
  26.                     }   
  27.                 }   
  28.             };   
  29.   
  30.             t0.start();   
  31.             // Give t time to get going...   
  32.             Thread.sleep(100);   
  33.             //t0.stop();   
  34.             t1.start();   
  35.         } catch (Throwable t) {   
  36.             System.out.println("Caught in main: " + t);   
  37.             t.printStackTrace();   
  38.         }   
  39.   
  40.     }  
[java] view plaincopy
 
  1. public static void main(String[] args) {  
  2.         final Object lock = new Object();  
  3.         try {  
  4.             Thread t0 = new Thread() {  
  5.                 public void run() {  
  6.                     try {  
  7.                         synchronized (lock) {  
  8.                             System.out.println("thread->" + getName()  
  9.                                     + " acquire lock.");  
  10.                             sleep(3000);// sleep for 3s  
  11.                             System.out.println("thread->" + getName()  
  12.                                     + " release lock.");  
  13.                         }  
  14.                     } catch (Throwable ex) {  
  15.                         System.out.println("Caught in run: " + ex);  
  16.                         ex.printStackTrace();  
  17.                     }  
  18.                 }  
  19.             };  
  20.   
  21.             Thread t1 = new Thread() {  
  22.                 public void run() {  
  23.                     synchronized (lock) {  
  24.                         System.out.println("thread->" + getName()  
  25.                                 + " acquire lock.");  
  26.                     }  
  27.                 }  
  28.             };  
  29.   
  30.             t0.start();  
  31.             // Give t time to get going...  
  32.             Thread.sleep(100);  
  33.             //t0.stop();  
  34.             t1.start();  
  35.         } catch (Throwable t) {  
  36.             System.out.println("Caught in main: " + t);  
  37.             t.printStackTrace();  
  38.         }  
  39.   
  40.     }  

 

 

当没有进行t0.stop()方法的调用时, 可以发现,两个线程争用锁的顺序是固定的。

 

输出:

thread->Thread-0 acquire lock.
thread->Thread-0 release lock.
thread->Thread-1 acquire lock.

 

但调用了t0.stop()方法后,(去掉上面的注释//t0.stop();),可以发现,t0线程抛出了ThreadDeath error并且t0线程释放了它所占有的锁。

 

输出:

thread->Thread-0 acquire lock.
thread->Thread-1 acquire lock.
Caught in run: java.lang.ThreadDeath
java.lang.ThreadDeath
 at java.lang.Thread.stop(Thread.java:715)
 at com.yezi.test.timeout.ThreadStopTest.main(ThreadStopTest.java:40)

 

 

从上面的程序验证结果来看,thread.stop()确实是不安全的。它的不安全主要是针对于第二点:释放该线程所持有的所有的锁。一般任何进行加锁的代码块,都是为了保护数据的一致性,如果在调用thread.stop()后导致了该线程所持有的所有锁的突然释放,那么被保护数据就有可能呈现不一致性,其他线程在使用这些被破坏的数据时,有可能导致一些很奇怪的应用程序错误。

 

 

 

如何正确停止线程

关于如何正确停止线程,这篇文章(how to stop thread)给出了一个很好的答案, 总结起来就下面3点(在停止线程时):

1. 使用violate boolean变量来标识线程是否停止

2. 停止线程时,需要调用停止线程的interrupt()方法,因为线程有可能在wait()或sleep(), 提高停止线程的即时性

3. 对于blocking IO的处理,尽量使用InterruptibleChannel来代替blocking IO

 

核心如下:

 

If you are writing your own small thread then you should follow the following example code.

    private volatile Thread myThread;
    public void stopMyThread() {
        Thread tmpThread = myThread;
        myThread = null;
        if (tmpThread != null) {
            tmpThread.interrupt();
        }
    }
    public void run() {
        if (myThread == null) {
           return; // stopped before started.
        }
        try {
            // all the run() method's code goes here
            ...
            // do some work
            Thread.yield(); // let another thread have some time perhaps to stop this one.
            if (Thread.currentThread().isInterrupted()) {
               throw new InterruptedException("Stopped by ifInterruptedStop()");
            }
            // do some more work
            ...
        } catch (Throwable t) {
           // log/handle all errors here
        }
    }


转自:http://blog.csdn.net/liranke/article/details/8270543
分享到:
评论

相关推荐

    为什么不鼓励使用 Thread.stop?

    NULL 博文链接:https://yxhcquedu.iteye.com/blog/859199

    最新版的DebuggingWithGDB7.05-2010

    5.4 Stopping and Starting Multi-thread Programs . . . . . . . . . . . . . . . . . 5.4.1 All-Stop Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.4.2 Non-...

    Java中interrupt的使用.docx

    在java的api中有stop、suspend等方法可以达到目的,但由于这些方法在使用上存在不安全性,会带来不好的副作用,不建议被使用。具体原因可以参考Why is Thread.stop deprecated。 在本文中,将讨论中断在java中的...

    java核心知识点整理.pdf

    本地方法区(线程私有) ................................................................................................................ 23 2.2.4. 堆(Heap-线程共享)-运行时数据区 ...........................

    Debugging with GDB --2007年

    5.4 Stopping and starting multi-thread programs . . . . . . . . . . . . . 6 Examining the Stack . . . . . . . . . . . . . . . . . . . . . . 51 6.1 6.2 6.3 6.4 6.5 6.6 7 Stack frames . . . . . . . . . ...

    thread stop tools

    thread stop;thread stop不错呀

    JAVA核心知识点整理(有效)

    2.2.3. 本地方法区(线程私有) ................................................................................................................ 23 2.2.4. 堆(Heap-线程共享)-运行时数据区 .....................

    Java并发编程实践

    1.3.4 使用Stop 终止线程........................................................................................18 1.3.5 结束程序的执行.....................................................................

    java解惑--异常地危险

    在JDK1.2中,Thread.stop、Thread.suspend以及其他许多线程相关的方法都因为它们不安全而不推荐使用了。下面的方法展示了你用Thread.stop可以实现的可怕事情之一

    Java並發編程實踐基礎

    1.3.4 使用Stop 终止线程........................................................................................18 1.3.5 结束程序的执行.....................................................................

    Debugging with GDB --2003年6.0

    5.4 Stopping and starting multi-thread programs . . . . . . . . . . . . . 6 Examining the Stack . . . . . . . . . . . . . . . . . . . . . . 53 6.1 6.2 6.3 6.4 7 Stack frames . . . . . . . . . . . . . ...

    在MatlabGUI里面启动或者暂停Simulink模型-start_and_stop.mdl

    在MatlabGUI里面启动或者暂停Simulink模型-start_and_stop.mdl 针对这个问题:https://www.ilovematlab.cn/thread-23233-1-1.html 现在我做一个集中解答,从mathworks那里学习了一下。 第一步:创建你自己的...

    在MatlabGUI里面启动或者暂停Simulink模型-start_and_stop_gui.m

    start_and_stop.mdl 第二步:创建自己的GUI, 这个论坛里也有例子,我们使用以下文件。 start_and_stop_gui.fig start_and_stop_gui.m ...

    j记事本.zip

    reader.SpeakAsync("欢迎使用 Virus 专用记事本 "); Thread.Sleep(1500); axWindowsMediaPlayer1.URL = this.textBox1.Text; panel2.BackgroundImage = Image.FromFile(this.textBox6.Text); ...

    JAVA并发编程实践-线程的关闭与取消-学习笔记

    java中没有提供任何机制,来安全是强迫线程停止手头的工作,Thread.stop和 Thread.suspend方法存在严重的缺陷,不能使用。程序不应该立即停止,应该采用中断这种协作机制来处理,正确的做法是:先清除当前进程中的...

    DebuggingWithGDB 6.8-2008

    5.4 Stopping and Starting Multi-thread Programs . . . . . . . . . . . . . . . . 6 Examining the Stack . . . . . . . . . . . . . . . . . . . . . . 61 6.1 6.2 6.3 6.4 7 Stack Frames . . . . . . . . . . ...

    在MatlabGUI里面启动或者暂停Simulink模型-start_and_stop_gui.fig

    start_and_stop.mdl 第二步:创建自己的GUI, 这个论坛里也有例子,我们使用以下文件。 start_and_stop_gui.fig start_and_stop_gui.m ...

    多线程,高并发.zip

    1. stop() 和 suspend() 方法为何不推荐使用? 反对使用 stop(),是因为它不安全。它会解除由线程获取的所有锁定,而且如果对象 处于一种不连贯状态,那么其他线程能在那种状态下检查和修改它们。结果很难检查出 ...

    Debugging with GDB --2001年5.3

    Table of Contents Summary of GDB . . . . . . . . ....Free software ....Free Software Needs Free Documentation ....Contributors to GDB ....1 A Sample GDB Session ....2 Getting In and Out of GDB ....Invoking GDB ....

    thrift服务端和客户端实现Nifty.zip

    然后使用此包就可以快速发布出基于netty的高效的服务端和客户端代码。 示例: public void startServer() { // Create the handler MyService.Iface serviceInterface = new MyServiceHandler(); // Create...

Global site tag (gtag.js) - Google Analytics