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