為什么不推薦使用Thread.interrupted作為線程終止的判讀條件


  寫一個線程類,個人習慣如下:

class MyWorkRunnable implements Runnable {
        volatile Thread mTheThread = null;
        @Override
        public void run() {
            if (mTheThread != Thread.currentThread()) {
                throw new RuntimeException();// 防止外部調用Thread.start方法啟動該線程
            }
            while (!Thread.interrupted()) {
                // 處理所要處理的工作
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    mTheThread.interrupt();        //此處不要忘記!!
                }
            }
        }
        public void start() {
            mTheThread = new Thread(this);
            mTheThread.start();
        }
        public void stop() {
            if (mTheThread != null) {
                mTheThread.interrupt();
                try {
                    mTheThread.join(); // 等待線程徹底結束
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    mTheThread.interrupt();
                }
            }
        }

  乍一看,沒有多余的標志位來作為是否繼續執行的條件,代碼很整潔很干凈,但是看到一些經典教材上面,往往會附加個標志位,比如:    

  while(!Thread.interrupted() && mKeepWork)

  相信我們很多人會很疑惑,為什么作者要多此一舉?第一種方式不是更加完美嗎?直到今天才發現原因。。

  在android里,我們通常會在子線程中渲染SurfaceView,如下面的代碼所示:

    Canvas canvas = getHolder().lockCanvas();
    if (canvas != null) {
        // 用canvas繪圖
        getHolder().unlockCanvasAndPost(canvas);
    }

  如果在我所寫的線程類中執行上面的工作,那么在stop時,可能導致死鎖!人人都痛恨死鎖,為什么會死鎖呢?我一度懷疑是android的一個bug。。在糾結這個問題一周后,終於找到了原因。原來,當界面無效(比如尚未創建成功或者已經被銷毀了)時,getHolder().lockCanvas() 方法會sleep 100毫秒,用以釋放出CPU資源(your calls will be throttled to a slow rate in order to avoid consuming CPU)。然而,當sleep方法拋出InterruptedException后,會取消線程的中斷狀態,但是在這個函數里,設計者卻把sleep的異常給swallow了。因此,在調用了mTheThread.interrupt()之后,線程的中斷狀態被sleep給取消了,導致在while里,條件永遠是成立的。而線程不退出,stop函數里的join函數也會一直阻塞,因而出現死鎖。

  加個標志位是解決這個問題的一個很好的選擇。重寫run代碼如下:  

     @Override
        public void run() {
            if (mTheThread != Thread.currentThread()) {
                throw new RuntimeException();
            }
            while (!Thread.interrupted() && mTheThread != null) {// 如果標志位為null,不再繼續。
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();    //mTheThread可能已經為空了,因此用Thread.currentThread()替代之
                }
            }
        }

  lockCanvas里簡單捕獲中斷異常的做法是不提倡的,一定要養成習慣,不要將中斷異常輕易捕獲后不管了。但是換句話說這種代碼也是無法避免的,那么我們只能加個標志位作為判斷條件了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM