Difference between Daemon and Non Daemon thread?

本文深入探讨了Java中守护线程和用户线程的区别与用途,通过示例代码展示了如何创建和使用守护线程,以及它们在程序生命周期中的作用。
In java we have two type of Threads :
Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our programm code. JVM doesn't terminates unless all the user thread terminate.

On the other hand we have Daemon threads. These threads are generally 'Service provider' threads. They should not be used to execute your program code but system code. These thread run in parallel to your code but JVM can kill them anytime. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus you should never depend on daemon thread to perform any program code.

 

Basically daemon threads exist only to do some work for non-daemon threads. If the only threads left in the JVM are daemon, then your program exits (terminates).
You might want to check and run the code below. You'll notice that when making thread t daemon, it exits immediately after the only non-daemon thread (the main thread) finishes - i.e. the daemon thread has not time to count from 10 to 1. But if you make thread t non-daemon, it finishes its job to the end (counting from 10 to 1).

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);
		t.start();

		System.out.println("Main thread waiting...");
		SECONDS.sleep(6);
		System.out.println("Main thread exited.");
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值