一、守护线程的使用
在Java中有两类线程:User Thread(用户线程)、Daemon Thread(守护线程)
User和Daemon两者几乎没有区别,唯一的不同之处就在于虚拟机的离开:如果 User Thread已经全部退出运行了,只剩下Daemon Thread存在了,虚拟机也就退出了。 因为没有了被守护者,Daemon也就没有工作可做了,也就没有继续运行程序的必要了。
注意点:
(1) thread.setDaemon(true)必须在thread.start()之前设置,否则会跑出一个IllegalThreadStateException异常。你不能把正在运行的常规线程设置为守护线程。
(2) 在Daemon线程中产生的新线程也是Daemon的。
(3) 不要认为所有的应用都可以分配给Daemon来进行服务,比如读写操作或者计算逻辑。
二、线程类通过本类方法启动线程
实现Runnable 或者继承 Thread 的类,可以在其他方法启动本类。有很多时候,为了交由一个方法统一管理。启动交由其中固定方法来启动,下面做一下展示。
public class DaemonTest {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.startUp();
}
static class MyThread implements Runnable{
public void startUp() throws InterruptedException {
Thread thread = new Thread(this);
thread.setName(this.getClass().getSimpleName() + "-thread");
thread.setDaemon(true);
thread.start();
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName()+"已经启动");
}
@Override
public void run() {
int count = 1;
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+count);
}
}
}
}
通过下面的打印结果可以看出当主线程结束,守护线程也结束。
打印结果:
MyThread-thread1
MyThread-thread1
MyThread-thread1
main已经启动