JAVA并发编程——守护线程(Daemon Thread)

来源:互联网 发布:ubuntu 16.04 lts ati 编辑:程序博客网 时间:2024/06/05 15:12

在Java中有两类线程:用户线程 (User Thread)、守护线程 (Daemon Thread)。

所谓守护 线程,是指在程序运行的时候在后台提供一种通用服务的线程,比如垃圾回收线程就是一个很称职的守护者,并且这种线程并不属于程序中不可或缺的部分。因此,当所有的非守护线程结束时,程序也就终止了,同时会杀死进程中的所有守护线程。反过来说,只要任何非守护线程还在运行,程序就不会终止。

用户线程和守护线程两者几乎没有区别,唯一的不同之处就在于虚拟机的离开:如果用户线程已经全部退出运行了,只剩下守护线程存在了,虚拟机也就退出了。 因为没有了被守护者,守护线程也就没有工作可做了,也就没有继续运行程序的必要了。

将线程转换为守护线程可以通过调用Thread对象的setDaemon(true)方法来实现。在使用守护线程时需要注意一下几点:

(1) thread.setDaemon(true)必须在thread.start()之前设置,否则会跑出一个IllegalThreadStateException异常。你不能把正在运行的常规线程设置为守护线程。 

(2) 在Daemon线程中产生的新线程也是Daemon的。

(3)守护线程应该永远不去访问固有资源,如文件、数据库,因为它会在任何时候甚至在一个操作的中间发生中断。

实例代码:

package com.lqh.threadpool;import java.util.concurrent.TimeUnit;public class Daemons {public static void main(String[] args) throws InterruptedException {System.out.println("main thread isDaemon = " + Thread.currentThread().isDaemon());Thread t = new Thread(new Daemon());t.setDaemon(true);t.start();System.out.println("t.isDaemon = " + t.isDaemon());TimeUnit.SECONDS.sleep(1);}}class Daemon implements Runnable {private Thread[] threads = new Thread[10];@Overridepublic void run() {try {for(int i=0; i<threads.length; i++) {threads[i] = new Thread(new DaemonSpawn());threads[i].start();System.out.println("DaemonSpawn " + i + " started..");}Thread.sleep(500);for(int i=0; i<threads.length; i++) {System.out.println("DaemonSpawn [" + i + "] thread isDaemon = " + threads[i].isDaemon());}} catch (InterruptedException e) {e.printStackTrace();}while(true) {Thread.yield();}}}class DaemonSpawn implements Runnable {@Overridepublic void run() {while(true) {Thread.yield();}}}

运行结果如下:

main thread isDaemon = falset.isDaemon = trueDaemonSpawn 0 started..DaemonSpawn 1 started..DaemonSpawn 2 started..DaemonSpawn 3 started..DaemonSpawn 4 started..DaemonSpawn 5 started..DaemonSpawn 6 started..DaemonSpawn 7 started..DaemonSpawn 8 started..DaemonSpawn 9 started..DaemonSpawn [0] thread isDaemon = trueDaemonSpawn [1] thread isDaemon = trueDaemonSpawn [2] thread isDaemon = trueDaemonSpawn [3] thread isDaemon = trueDaemonSpawn [4] thread isDaemon = trueDaemonSpawn [5] thread isDaemon = trueDaemonSpawn [6] thread isDaemon = trueDaemonSpawn [7] thread isDaemon = trueDaemonSpawn [8] thread isDaemon = trueDaemonSpawn [9] thread isDaemon = true

以上结果说明了守护线程中产生的新线程也是守护线程。

如果将mian函数中的TimeUnit.SECONDS.sleep(1);注释掉,运行结果如下:

main thread isDaemon = falset.isDaemon = trueDaemonSpawn 0 started..DaemonSpawn 1 started..DaemonSpawn 2 started..DaemonSpawn 3 started..DaemonSpawn 4 started..DaemonSpawn 5 started..DaemonSpawn 6 started..DaemonSpawn 7 started..DaemonSpawn 8 started..DaemonSpawn 9 started..

转自:http://www.cnblogs.com/luochengor/archive/2011/08/11/2134818.html