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

该博客通过一个代码示例展示了Java中设置线程为守护线程(daemon)与用户线程的不同。当主线程结束时,如果工作线程是用户线程,它将继续运行;而如果是守护线程,则会随着主线程的终止而停止。内容涉及到线程的生命周期和Java多线程概念。
摘要由CSDN通过智能技术生成

以上所有答案都很好。这里有一个简单的代码片段,来说明两者之间的区别。中的true和false的每个值都尝试它。setDaemon.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

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值