java - setDaemon(false) 是多余的吗?

标签 java multithreading daemon

想问线程启动前的setDaemon(false)是否多余(构造函数中已经有setDaemon(false)),如果不是有什么区别? 无论如何,我从某个网站复制了这段代码。

import java.lang.*;

class adminThread extends Thread {

   adminThread() {
   setDaemon(false);
   }

   public void run() {
   boolean d = isDaemon();
   System.out.println("daemon = " + d);
   }
}

public class ThreadDemo {

  public static void main(String[] args) throws Exception {

   Thread thread = new adminThread();
   System.out.println("thread = " + thread.currentThread());
   thread.setDaemon(false);

   // this will call run() method
   thread.start();
  }
} 

这是我从以下位置获得的代码:https://www.tutorialspoint.com/java/lang/thread_setdaemon.htm

感谢和问候。

最佳答案

is the setDaemon(false) before thread start is redundant (in the constructor is already setDaemon(false)) or not, if not what is the difference?

不是多余的。线程从创建它的父线程的守护进程状态中获取其守护进程标志。创建 adminThread 的线程可能已经是守护线程,因此如果您需要强制它成为守护线程,您需要显式设置它。

来自Thread.init(...)方法:

Thread parent = currentThread();
...
this.daemon = parent.isDaemon();

因此,如果您希望某个线程成为守护程序或不专门指定,您应该在调用 start() 之前专门设置它。

关于代码的一些其他注释。类应该以大写字母开头,因此应该是AdminThread。还建议实现 Runnable 而不是扩展 Thread,因此它实际上应该是 AdminRunnable。所以代码看起来像:

class AdminThread implements Runnable {
    // no constructor needed
    public void run() {
       ...
    }
}
...
Thread thread = new Thread(new AdminThread());
thread.setDaemon(false);
thread.start();

关于java - setDaemon(false) 是多余的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41788304/

相关文章:

c++ - 如何在不违反 const 正确性的情况下使用 std::lock_guard?

ruby - 为什么 Ruby 服务器仅在守护进程时才会产生僵尸?

java - 如何避免两个计划作业冲突导致 ObjectOptimisticLockingFailureException

iphone - Dispatch Queue 和 NSOperationQueue 的区别

java - 如何在另一个线程中重新抛出异常以捕获 block

c - 检测systemd的可靠方法

ruby-on-rails - rails 3 中的脚本/运行器

java - hibernate @CollectionOfElements 和@Parent

java - 在运行时动态解析 .proto 文本文件以生成描述符

java - 如何告诉 Spring Boot 使用另一个数据库进行测试?