java thread programming 1.5 – Gracefully Stopping Threads

來源:互聯網
上載者:User

interrupt()
While one thread is running, another thread can interrupt it by invoking its corresponding Thread object’s interrupt() method:public void interrupt() This method simply sets a flag in the destination thread indicating that it has been interrupted and returns right away. It is possible that a SecurityException will be thrown by interrupt(), indicating that the thread requesting the interrupt does not have permission to interrupt the other thread. The security check is done by invoking the checkAccess() method on Thread, which in turn checks whether a SecurityManager has been installed, and if so, invokes its checkAccess(Thread) method. An in-depth exploration of security in Java is beyond the scope of this book, but you should note that some methods of Thread and ThreadGroup could throw SecurityExceptions. 本方法修改線程標誌位表明線程已經中斷,立刻返回,在某些安全要求比較高的環境(applet)如果存在SecuityManager可能會拋出SecurityException異常。  isInterrupted()
You can check the interrupted status of any thread by invoking the isInterrupted() method on the Thread object:public boolean isInterrupted() This does not alter the status, but simply returns true if the thread has been interrupted and its interrupted flag has not yet been cleared. 探測線程是否中斷,本函數執行完畢,中斷標誌位不被清除  Thread.interrupted()
You can use the Thread.interrupted() method to check (and implicitly reset to false) the interrupted status of the current thread:public static boolean interrupted() Because it is static, it cannot be invoked on a particular thread, but can only report the interrupted status of the thread that invoked it. This method returns true if the thread has been interrupted and its interrupted flag has not yet been cleared. Unlike isInterrupted(), it automatically resets the interrupted flag to false. Invoking Thread.interrupted() a second time would always return false unless the thread was reinterrupted. Listing 5.4 shows an example of how you can use Thread.interrupted().  探測線程是否中斷,本程式執行完畢,中斷標誌重設為false   Deprecated Methods suspend() and resume()  The Thread API contains two deprecated methods that are used to temporarily stop and later restart a thread:public final void suspend()public final void resume() Methods and classes are deprecated by Sun Microsystems to indicate that developers should avoid using them. A deprecated method can still be used, but when the code is compiled, a warning is issued. Deprecation is used to indicate a method or class is obsolete or dangerous and may be removed from future releases of the JDK. Although you may still use deprecated methods, you should use them sparingly and only when absolutely necessary. suspend()掛起線程resume()恢複線程執行@Deprecation 表明此方法不推薦使用,在jdk將來版本可能會被剔出 The suspend() method is deprecated as of JDK 1.2 because if a thread is suspended at an inopportune time—such as when it is holding a lock for a shared resource—a deadlock condition may result. I explain and demonstrate deadlocks in Chapter 7, “Concurrent Access to Objects and Variables,” but let it suffice to say for now that a deadlock is a very bad thing and can cause a program to freeze up on a user. Even when locks are not involved, a thread might be suspended while in the middle of a long procedure that really should not be left in a partially completed state. The resume() method is deprecated because without any use of suspend(), it is not needed. 不推薦使用suspend()的原因:1、  當線程佔有某些共用資源時,將其掛起,很容易造成死結,2、  當執行某些不能被部分完成的大操作時,線程可能會被掛起不推薦使用resume()的原因是因為不推薦使用suspend()  Deprecated Method stop()
At times, one of the additional threads spawned in a multithreaded program is no longer needed, but it continues to execute statements—perhaps in an infinite loop. The Thread API includes a stop() method to abruptly terminate a thread’s execution:public final void stop() When this method is invoked on a thread, the thread immediately throws a java.lang.ThreadDeath error (a subclass of java.lang.Error, which itself is a subclass of java.lang.Throwable). This exception propagates up the method call stack, executing any finally clauses present and releasing any locks that are currently held. Ultimately, this exception causes run() to abruptly return, and the thread dies. 調用stop()方法時,線程會立刻拋出ThreadDeath error(java.lang.Error的子類,java.lang.Error本身是java.lang.Throwable的子類),線程會釋放所有鎖,run()立刻返回,線程死亡 The stop() method is deprecated as of JDK 1.2 because it can lead to corrupted data in objects. One problem is that when a thread is stopped abruptly, there is little opportunity to perform any cleanup work. Another problem is that when stop() is invoked on a thread, the thread releases all the locks it is currently holding. The locks are definitely being held for a good reason—probably to keep other threads from accessing data elements that are not yet in a consistent state. This sudden release of the locks may leave some data in some objects in an inconsistent state with no warning about the possible corruption. In many cases, there are other ways to have a thread return from run() in an orderly manner that leaves all objects in a consistent state. stop被取消的原因:1、  當一個線程被粗暴中止,可能還沒有進行清除工作2、  鎖機制就是防止訪問共同資源其他線程處於不連續狀態,線程被stop之後,會釋放其擁有所有鎖,造成其它線程不連續 An Alternative to stop():變通方法AlternateStop.java源碼/* * Created on 2005-7-8 * * Java Thread Programming - Paul Hyde  * Copyright ? 1999 Sams Publishing * Jonathan Q. Bo 學習筆記 *  */ package org.tju.msnrl.jonathan.thread.chapter1; /** * @author Jonathan Q. Bo from TJU MSNRL * * Email:jonathan.q.bo@gmail.com * Blog:blog.csdn.net/jonathan_q_bo *      blog.yesky.net/jonathanundersun *  * Enjoy Life with Sun! *  */ public class AlternateStop implements Runnable {     private Thread runThread;        private volatile boolean stopRequest;     /*      * @see java.lang.Runnable#run()     */    public void run() {        this.runThread = Thread.currentThread();        stopRequest = false;                int counter = 0;         while(!stopRequest){            System.out.println("running ... ... count = " + counter);            counter++;                        try{                Thread.sleep(300);            }catch(InterruptedException e){                Thread.currentThread().interrupt();            }        }    }        public void stopThread(){         this.stopRequest = true;        if(this.runThread != null){            this.runThread.interrupt();        }    }     public static void main(String[] args) {        AlternateStop at = new AlternateStop();        Thread newThread = new Thread(at);        newThread.start();        try{            Thread.sleep(2000);        }catch(InterruptedException e){            System.out.println(e.getMessage());        }        at.stopThread();    }}  Daemon ThreadsThreads that are marked as daemons stop in a whole new way. Daemon threads are used for background supporting tasks and are only needed while normal, nondaemon threads are still running. When the VM detects that the only remaining threads are daemon threads, it exits. If any nondaemon thread is still alive, the VM will not exit. Daemon threads provide a nice way of managing some sort of behind-the-scenes processing that is only necessary to support other nondaemon threads. 守護線程:當其他通常的非守護線程運行時,後台執行;當其他線程結束,剩下的都是守護線程時,虛擬機器停止守護線程。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.