java的线程的setDaemon()设为true时,怎么不能一直运行呢?代码有误么?该如何改?   
    
  谢先了!   
    
  import   java.util.*;     
  public   class   TimeCortrol   
  {   
  public   static   void   main(String   args[])   
  {     
  StartThread   tp1   =   new   StartThread();   
  tp1.start();   
  }   
  }   
  class   StartThread   extends   Thread   
  {   
  public   StartThread()   
  {   
  this.setDaemon(true);   
  }   
  public   void   run()   
  {   
  while(true)   
  {   
  try   
  {   
  System.out.println("***Deamon******");   
  }   
  catch(Exception   e)   
  {   
  System.out.println(e);   
  }   
  }   
  }   
  } 

解决方案 »

  1.   

     this.setDaemon(true);   你把这一行代码去掉才会一直运行,该行表示为守护线程。如果没有新线程创建或者子线程运行完毕,则它也会退出的。 你看看守护线程与新线程的关系吧。
      

  2.   

    this.setDaemon()意味着当前线程处于后台工作
      

  3.   

    你把tp1设成daemon,那么,主线程main做完,整个程序都结束。
    你在主线程中添点儿东西就行了
    import  java.util.*;    
      public  class  TimeCortrol  
      {  
      public  static  void  main(String  args[])  
      {    
      StartThread  tp1  =  new  StartThread();  
      tp1.start(); 
      for(int i=1;i<20;i++) 
      System.out.println("新曙光");

      }  
      }  
      class  StartThread  extends  Thread  
      {  
      public  StartThread()  
      {  
      this.setDaemon(true);  
      }  
      public  void  run()  
      {  
      while(true)  
      {  
      try  
      {  
      System.out.println("***Deamon******");  
      }  
      catch(Exception  e)  
      {  
      System.out.println(e);  
      }  
      }  
      }  
      } 
    daemon视频讲解
      

  4.   

    我觉得应该写成这样比较好吧public class ThreadTester {
        public static void main(String[] args)
                throws InterruptedException {
            StartThread thread = new StartThread();
            thread.start();
            Thread.sleep(1000);
        }}
    class StartThread extends Thread {
        public StartThread() {
            setDaemon(true);
        }    public void run() {
            while (true) {
                System.out.println("**** Deamon ******");
            }
        }
    }setDeamon的话线程变成后台线程了,运行程序后main已经退出,这里可以先让main线程小睡一下,这样就可以看到StartThread的输出了