java守护程序_什么是Java中的守护程序线程?

问题

谁能告诉我Java中的守护程序线程是什么?

#1 热门回答(532 赞)

守护程序线程是一个线程,它不会阻止JVM在程序完成但程序仍在运行时退出。守护程序线程的一个示例是垃圾收集。

你可以使用setDaemon(boolean)方法在线程启动之前更改Thread守护程序属性。

#2 热门回答(293 赞)

创建新线程时,它继承其父级的守护程序状态。

正常的线程和守护程序线程在退出时会发生什么不同。当JVM停止时,任何剩余的守护程序线程都被放弃:最后块不会被执行,堆栈也不会被解除 - JVM就会退出。由于这个原因,应该谨慎使用守护程序线程,并且将它们用于可能执行任何类型的I / O的任务是危险的。

#3 热门回答(150 赞)

以上所有答案都很好。这是一个简单的小代码片段,用于说明差异。尝试使用setDaemon中的每个true和false值。

public class DaemonTest {

public static void main(String[] args) {

new WorkerThread().start();

try {

Thread.sleep(7500);

} catch (InterruptedException e) {

// handle here exception

}

System.out.println("Main Thread ending") ;

}

}

class WorkerThread extends Thread {

public WorkerThread() {

// 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.

setDaemon(true);

}

public void run() {

int count = 0;

while (true) {

System.out.println("Hello from Worker "+count++);

try {

sleep(5000);

} catch (InterruptedException e) {

// handle exception here

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值