想问线程启动前的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/