關於Thread對象的suspend,resume,stop方法

1、做用java

    對於老式得磁帶錄音機,上面都會有,暫停,繼續,中止。Thread中suspend,resume,stop方法就相似。安全

    suspend,使線程暫停,可是不會釋放相似鎖這樣的資源。ide

    resume,使線程恢復,若是以前沒有使用suspend暫停線程,則不起做用。spa

    stop,中止當前線程。不會保證釋放當前線程佔有的資源。線程

2、代碼code

public static void main(String[] args) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i <= 10000; i ++) {
                System.out.println(i);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    thread.start();

    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    thread.suspend();                       //註釋1
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    thread.resume();                        //註釋2
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    thread.stop();                        //註釋3
    System.out.println("main end..");

}


    代碼中註釋1的地方,線程會暫停輸出,直到註釋2處才恢復運行,到了註釋3的地方,線程就被終止了。orm

    suspend,resume,stop這樣的方法都被標註爲過時方法,由於其不會保證釋放資源,容易產生死鎖,因此不建議使用。
資源

3、如何安全的暫停一個線程it

使用一個volatile修飾的boolean類型的標誌在循環的時候判斷是否已經中止。io

public class Test {
    public static void main(String[] args) {
        Task task = new Task();
        new Thread(task).start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        task.stop();
        System.out.println("main end...");
    }

    static class Task implements Runnable {
        static volatile boolean stop = false;

        public void stop() {
            stop = true;
        }

        @Override
        public void run() {
            int i = 0;
            while (!stop) {
                System.out.println(i++);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
相關文章
相關標籤/搜索