【Java多线程】之九:守护线程
来源:互联网 发布:java aop原理 编辑:程序博客网 时间:2024/05/06 10:36
When we create a Thread in java, by default it’s a user thread and if it’s running JVM will not terminate the program. When a thread is marked as daemon thread, JVM doesn’t wait it to finish and as soon as all the user threads are finished, it terminates the program as well as all the associated daemon threads.
Thread.setDaemon(true) can be used to create a daemon thread in java. Let’s see a small example of java daemon thread.
JavaDaemonThread
package com.journaldev.threads;public class JavaDaemonThread { public static void main(String[] args) throws InterruptedException { Thread dt = new Thread(new DaemonThread(), "dt"); dt.setDaemon(true); dt.start(); //continue program Thread.sleep(30000); System.out.println("Finishing program"); }}class DaemonThread implements Runnable{ @Override public void run() { while(true){ processSomething(); } } private void processSomething() { try { System.out.println("Processing daemon thread"); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }}
When we execute this program, JVM creates first user thread with main() function and then a daemon thread. When main function is finished, the program terminates and daemon thread is also shut down by JVM.
Here is the output of the above program.
Processing daemon threadProcessing daemon threadProcessing daemon threadProcessing daemon threadProcessing daemon threadProcessing daemon threadFinishing program
If we don’t set the thread to be run as daemon thread, the program will never terminate even after main thread is finished it’s execution. Try commenting the statement to set thread as daemon thread and run the program.
Usually we create a daemon thread for functionalities that are not critical to system, for example logging thread or monitoring thread to capture the system resource details and their state.
更多参考文章请点击这里!
- 【Java多线程】之九:守护线程
- java多线程之守护线程
- java多线程之守护线程(daemon thread)
- java多线程之守护线程(Daemon)
- JAVA.003 多线程之守护线程
- java多线程之守护线程(Daemon)
- java多线程-守护线程
- java多线程-守护线程
- Java 多线程 - 守护线程
- Java 多线程守护线程
- java多线程之守护线程和用户线程
- Java多线程基础--10之 线程优先级和守护线程
- 4.多线程之守护线程
- 多线程_线程控制之守护线程
- 多线程-线程控制之守护线程
- Java多线程-线程的调度(守护线程)
- java多线程:线程的调度-守护线程
- Java多线程 -- 线程的调度-守护线程
- windows device driver 小结感想
- 计算最小编辑距离
- mysql网络配置都需要修改哪些
- Android应用程序(APK)的构建过程
- Mac OS 升级svn客户端
- 【Java多线程】之九:守护线程
- leetcode 107 —— Binary Tree Level Order Traversal II
- hdu5348
- 棋盘问题
- linux右上角小键盘隐藏的解决方法
- 下列const的含义有什么
- LDA主题模型
- Unity3D之如何将包大小减少到极致
- Windows10屏蔽优酷视频广告