- public class Test14 {
-
- public static void main(String[] args) {
- T t = new T();
- //设置为守护守护线程
- t.setDaemon(true);
- t.start();
-
- System.out.println("hello");
- }
- }
- class T extends Thread
- {
- @Override
- public void run() {
- for (int i = 0 ; i < 50 ; i ++) {
- try {
- System.out.println(this.getName());
- Thread.sleep(100) ;
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(i);
- }
-
- }
-
- }
复制代码
运行结果:
hello
Thread-0
当新线程设置为守护线程时,主线程运行结束,新的线程也结束,也就是说守护线程为非守护线程服务,当非守护线程运行结束,守护线程也跟着停止。 |
|