守护线程

什么是守护线程

a.       在客户/服务器模式下,服务器的作用是等待用户发来请求,并按请求完成客户的工作

b.       守护线程是为其它线程提供服务的线程,如定时器线程

c.       守护线程一般应该是一个独立的线程,它的run()方法是一个无限循环

d.       守护线程与其它线程的区别是:如果守护线程是唯一运行着的线程,程序会自动退出

e.       把线程变成一个守护线程:r.setDeamon(true);

 

实例1

package com.bijian.thread;

import static java.util.concurrent.TimeUnit.*;  

public class DaemonTest {

	public static void main(String[] args) throws InterruptedException {  
        Runnable r = new Runnable() {  
            public void run() {  
                for (int time = 10; time > 0; --time) {  
                    System.out.println("Time #" + time);  
                    try {  
                        SECONDS.sleep(2);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        };
        
        Thread t = new Thread(r);  
        t.setDaemon(true);  // try to set this to "false" and see what happens  
        t.start();
        
        System.out.println("Main thread waiting...");  
        SECONDS.sleep(6);  
        System.out.println("Main thread exited.");  
    }  
}

 

运行结果:
Main thread waiting...
Time #10
Time #9
Time #8
Main thread exited.
Time #7

 

       t.setDaemon( true ); 语句改为 t.setDaemon( false ); 运行结果如下:
Main thread waiting...
Time #10
Time #9
Time #8
Main thread exited.
Time #7
Time #6
Time #5
Time #4
Time #3
Time #2
Time #1

  

实例2:

package com.bijian.thread;

public class MyThread extends Thread {

	public void run() {
		System.out.println("Daemon is " + isDaemon());
		while (true) {
			;
		}
	}
}

  

package com.bijian.thread;

public class UserDaemonThreadDemo {

	public static void main(String[] args) {
		if (args.length == 0)
			new MyThread().start();
		else {
			MyThread mt = new MyThread();
			mt.setDaemon(true);
			mt.start();
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
	}
}

 

       如果不设置参数,即 args. length == 0 ,运行结果如下:
Daemon is false

 

且程序一直运行

 

       如果随便设置一个参数,即args.length != 0,设置过程如下

 

 

 

 

      

 
       运行结果如下:

Daemon is true

 

且程序 1 秒后退出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值