Java 中 isDaemon() 方法的重要性?
守护线程是 java 中的低优先级线程,它在后台运行,主要由 JVM 创建,用于执行后台任务,例如垃圾回收 (GC)。
如果没有用户线程处于运行状态,那么即使守护线程正在运行,JVM 也会退出。守护线程的唯一目的是为用户线程服务。isDaemon() 方法可用于确定该线程是不是守护线程。
语法
Public boolean isDaemon()
示例
class SampleThread implements Runnable {
public void run() {
if(Thread.currentThread().isDaemon())
System.out.println(Thread.currentThread().getName()+" is daemon thread");
else
System.out.println(Thread.currentThread().getName()+" is user thread");
}
}
// Main class
public class DaemonThreadTest {
public static void main(String[] args){
SampleThread st = new SampleThread();
Thread th1 = new Thread(st,"Thread 1");
Thread th2 = new Thread(st,"Thread 2");
th2.setDaemon(true); // set the thread th2 to daemon.
th1.start();
th2.start();
}
}
输出
Thread 1 is user thread Thread 2 is daemon thread
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP