setDaemon(false) 是多余的?
setDaemon(false) is redundant?
想问下线程启动前的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
感谢和问候。
这是多余的,除非您正在编写一些从未知来源获取 Thread 对象的并发框架。在这种情况下,您可能希望执行该调用以确保它不是守护进程。
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();
想问下线程启动前的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
感谢和问候。
这是多余的,除非您正在编写一些从未知来源获取 Thread 对象的并发框架。在这种情况下,您可能希望执行该调用以确保它不是守护进程。
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();