java创建守护线程
创建过程:
1.实例化自定义继承Thread的类。
2.调用setDeamon方法,传入true。
3.完成
功能:
随着主线程的结束,守护线程也会结束,不再执行。
实现代码:
package com.threadtest;
public class Deamon
{
public static void main(String[] args)
{
DThread dt=new DThread();
dt.setDaemon(true);
dt.start();
try {
Thread.sleep(5000);//主线程休眠5s
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class DThread extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
{
System.out.println("aaa"+i);
try {
Thread.sleep(1000);//线程休眠1s
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
运行结果:
aaa0
aaa1
aaa2
aaa3
aaa4