您的位置:首页 > 编程语言 > Java开发

JAVA守护线程与用户线程的区别

2015-04-23 21:50 615 查看
public class DaemonTest {

public static void main(String[] args) {
new WorkerThread().start();
try {
Thread.sleep(7500);
} catch (InterruptedException e) {}
System.out.println("Main Thread ending") ;
}

}
class WorkerThread extends Thread {

public WorkerThread() {
setDaemon(true) ; // When false, (i.e. when it's a user thread),
// the Worker thread continues to run.
// When true, (i.e. when it's a daemon thread),
// the Worker thread terminates when the main
// thread terminates.
}

public void run() {
int count=0 ;
while (true) {
System.out.println("Hello from Worker "+count++) ;
try {
sleep(5000);
} catch (InterruptedException e) {}
}
}
}

简单理解:守护进程是不会阻止JVM的关闭的。当有用户线程运行时,JVM不能关闭。当没有用户线程运行时,有没有守护线程没关系,JVM都会关闭。
守护线程应用示例:java garbage collection。当没有线程运行时,不会产生垃圾,garbage collection也就没有发挥作用,JVM可以关闭。

守护线程应用背景:后台线程(比如可以收集某些系统状态的线程,发送email的线程,等不希望影响JVM的事情)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程