關於Thread物件的suspend,resume,stop方法(已過時)
阿新 • • 發佈:2019-02-04
一、作用
二、程式碼
程式碼中註釋1的地方,執行緒會暫停輸出,直到註釋2處才恢復執行,到了註釋3的地方,執行緒就被終止了。
suspend,resume,stop這樣的方法都被標註為過期方法,因為其不會保證釋放資源,容易產生死鎖,所以不建議使用。
三、如何安全的暫停一個執行緒
使用一個volatile修飾的boolean型別的標誌在迴圈的時候判斷是否已經停止。
對於老式的磁帶錄音機,上面都會有暫停,繼續,停止。Thread中suspend,resume,stop方法就類似。
suspend,使執行緒暫停,但是不會釋放類似鎖這樣的資源。
resume,使執行緒恢復,如果之前沒有使用suspend暫停執行緒,則不起作用。
stop,停止當前執行緒。不會保證釋放當前執行緒佔有的資源。
二、程式碼
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的地方,執行緒就被終止了。
suspend,resume,stop這樣的方法都被標註為過期方法,因為其不會保證釋放資源,容易產生死鎖,所以不建議使用。
三、如何安全的暫停一個執行緒
使用一個volatile修飾的boolean型別的標誌在迴圈的時候判斷是否已經停止。
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(); } } } } }