java守護線程的理解

來源:互聯網
上載者:User

標籤:ima   nts   方法   print   ext   i++   trace   dex   守護線程   

  1. package daemonThread;
  2. /*setDaemon(true)方法將線程設定為守護線程,線程的Daemon預設值為false
  3.  * 只要當前JVM執行個體中存在任何一個非守護線程沒有結束,守護線程就在工作
  4.  * 當進程中不存在非守護線程,則守護線程隨著JVM一同結束
  5.  * GC(記憶體回收行程)就是一個守護線程
  6.  * 本例中main線程雖然先結束,但是testThread線程還在工作,所以只有當testThread線程也結束,才停止列印i */
  7. class MyThread extends Thread{
  8.  private int i = 0;
  9.  @Override
  10.  public void run(){
  11.   super.run();
  12.   try{
  13.    while(true){
  14.     i++;
  15.     System.out.println("i="+i);
  16.     Thread.sleep(1000);
  17.    }
  18.   }catch(InterruptedException ie){
  19.    ie.printStackTrace();
  20.   }
  21.  }
  22. }
  23. class testThread extends Thread{
  24.  @Override
  25.  public void run(){
  26.   try{
  27.    Thread.sleep(10000); //testThread線程約10秒後結束
  28.    System.out.println(Thread.currentThread().getName()+"線程結束!");
  29.   }catch(InterruptedException ie){
  30.    ie.printStackTrace();
  31.   }
  32.  }
  33. }
  34. public class Run {
  35.  public static void main(String[] args) {
  36.   // TODO Auto-generated method stub
  37.   try{
  38.    MyThread thread = new MyThread();
  39.    thread.setName("thread");
  40.    thread.setDaemon(true); //將thread線程設為守護線程
  41.    thread.start();
  42.    testThread t = new testThread();
  43.    t.setName("testThread");
  44.    t.start();
  45.    Thread.sleep(5000);  //main線程在這裡停留5秒
  46.    System.out.println("主線程結束了");//5秒後main線程結束了,但是testThread線程還在執行,所以守護線程繼續工作
  47.   
  48.    /*當所有線程都結束時,thread線程也隨之結束*/
  49.   }catch(InterruptedException ie){
  50.    ie.printStackTrace();
  51.   }
  52.  }
  53. }

運行結果如

 

java守護線程的理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.