public class Test {
/**
* User:liluzhong
* Date: Dec 10, 2017
* Time: 7:16:55 PM
*/
public static void main(String[] args) throws Exception{
DaemonThread t = new DaemonThread();
t.setDaemon(true);//this is set t thread as a daemon thread.
t.start();
Thread.sleep(2000);
System.out.println("main thread exit.");
}
}
class DaemonThread extends Thread {
@Override
public void run() {
for(int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i=" + i);
}
}
}
/**
* User:liluzhong
* Date: Dec 10, 2017
* Time: 7:16:55 PM
*/
public static void main(String[] args) throws Exception{
DaemonThread t = new DaemonThread();
t.setDaemon(true);//this is set t thread as a daemon thread.
t.start();
Thread.sleep(2000);
System.out.println("main thread exit.");
}
}
class DaemonThread extends Thread {
@Override
public void run() {
for(int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i=" + i);
}
}
}
本文提供了一个简单的Java守护线程(Daemon Thread)使用示例。在示例中,创建了一个名为`DaemonThread`的线程,并通过`setDaemon(true)`将其设置为守护线程。主线程启动该守护线程后,休眠2秒然后退出,而守护线程继续运行,输出从0到9的数字。

被折叠的 条评论
为什么被折叠?



