有人能告诉我Java中的守护线程是什么吗?
当前回答
Java中的守护线程是指运行在后台的线程,主要由JVM创建,用于执行后台任务,如垃圾收集和其他家政任务。
注意事项:
Any thread created by main thread, which runs main method in Java is by default non daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main thread is a non daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true). Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.
Java中守护线程与非守护线程的区别:
1) JVM在存在之前不会等待任何守护线程完成。
2)当JVM终止时,守护线程与用户线程被区别对待,最终块不被调用,堆栈不受伤,JVM只是退出。
其他回答
守护线程是在程序完成但线程仍在运行时不阻止JVM退出的线程。守护进程线程的一个例子是垃圾收集。
您可以使用setDaemon(boolean)方法在线程启动之前更改线程守护进程属性。
传统上,UNIX中的守护进程是那些不断在后台运行的进程,就像Windows中的服务一样。
Java中的守护线程是不阻止JVM退出的线程。特别是当只剩下守护线程时,JVM将退出。您可以通过调用线程上的setDaemon()方法来创建一个。
读取Daemon线程。
守护线程是在后台执行一些任务的线程,比如处理请求或应用程序中可能存在的各种chronjob。
当你的程序只剩下守护线程时,它将退出。这是因为这些线程通常与普通线程一起工作,并提供事件的后台处理。
你可以使用setDaemon方法指定一个线程是守护线程,它们通常不会退出,也不会被中断。当应用程序停止时,它们就会停止。
让我们只讨论工作示例中的代码。我喜欢russ上面的回答,但为了消除我的疑虑,我稍微加强了一下。我运行了两次,一次工作线程设置为deamon true (deamon线程),另一次设置为false(用户线程)。它确认守护线程在主线程结束时结束。
public class DeamonThreadTest {
public static void main(String[] args) {
new WorkerThread(false).start(); //set it to true and false and run twice.
try {
Thread.sleep(7500);
} catch (InterruptedException e) {
// handle here exception
}
System.out.println("Main Thread ending");
}
}
class WorkerThread extends Thread {
boolean isDeamon;
public WorkerThread(boolean isDeamon) {
// 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.
this.isDeamon = isDeamon;
setDaemon(isDeamon);
}
public void run() {
System.out.println("I am a " + (isDeamon ? "Deamon Thread" : "User Thread (none-deamon)"));
int counter = 0;
while (counter < 10) {
counter++;
System.out.println("\tworking from Worker thread " + counter++);
try {
sleep(5000);
} catch (InterruptedException e) {
// handle exception here
}
}
System.out.println("\tWorker thread ends. ");
}
}
result when setDeamon(true)
=====================================
I am a Deamon Thread
working from Worker thread 0
working from Worker thread 1
Main Thread ending
Process finished with exit code 0
result when setDeamon(false)
=====================================
I am a User Thread (none-deamon)
working from Worker thread 0
working from Worker thread 1
Main Thread ending
working from Worker thread 2
working from Worker thread 3
working from Worker thread 4
working from Worker thread 5
working from Worker thread 6
working from Worker thread 7
working from Worker thread 8
working from Worker thread 9
Worker thread ends.
Process finished with exit code 0
答案已经有很多了;然而,也许我可以更清楚地解释这一点,因为当我阅读Daemon Threads时,最初,我有一种感觉,我很好地理解了它;然而,在玩了它并调试了一下之后,我发现了一个奇怪的行为。
我被教导:
如果我想让线程在主线程有序完成执行后立即死亡,我应该将其设置为Diamond。
我尝试了什么:
我从主线程中创建了两个线程,我只将其中一个设置为菱形; 在主线程有序完成执行后,那些新创建的线程都没有退出,但我预计,守护线程应该已经退出; 我浏览了许多博客和文章,到目前为止,我找到的最好、最清晰的定义来自《Java并发实践》一书,它非常清楚地指出:
7.4.2守护线程
Sometimes you want to create a thread that performs some helper function but you don’t want the existence of this thread to prevent the JVM from shutting down. This is what daemon threads are for. Threads are divided into two types: normal threads and daemon threads. When the JVM starts up, all the threads it creates (such as garbage collector and other housekeeping threads) are daemon threads, except the main thread. When a new thread is created, it inherits the daemon status of the thread that created it, so by default any threads created by the main thread are also normal threads. Normal threads and daemon threads differ only in what happens when they exit. When a thread exits, the JVM performs an inventory of running threads, and if the only threads that are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any remaining daemon threads are abandoned— finally blocks are not executed, stacks are not unwound—the JVM just exits. Daemon threads should be used sparingly—few processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for “housekeeping” tasks, such as a background thread that periodically removes expired entries from an in-memory cache.
推荐文章
- 指定的子节点已经有一个父节点。你必须先在子对象的父对象上调用removeView() (Android)
- 对于一个布尔字段,它的getter/setter的命名约定是什么?
- 如何获得当前屏幕方向?
- 如何在Android中渲染PDF文件
- 如何计算一个元素在列表中出现的次数
- c++中类似于java的instanceof
- 我如何解决错误“minCompileSdk(31)指定在一个依赖的AAR元数据”在本机Java或Kotlin?
- 如何POST表单数据与Spring RestTemplate?
- Mockito中检测到未完成的存根
- 我应该如何复制字符串在Java?
- “while(true)”循环有那么糟糕吗?
- 这个方法签名中的省略号(…)是干什么用的?
- Java:如何测试调用System.exit()的方法?
- 带有返回类型的Java方法在没有返回语句的情况下编译
- Java“此语言级别不支持lambda表达式”