User和Daemon两者几乎没有区别,唯一的不同之处就在于虚拟机的离开:如果 User Thread已经全部退出运行了,只剩下Daemon Thread存在了,虚拟机也就退出了。 因为没有了被守护者,Daemon也就没有工作可做了,也就没有继续运行程序的必要了。我们知道JVM里面有垃圾回收器的存在,其实垃圾回收就可以认为是守护线程的功能之一。
线程创建的两种方式
1)通过实现Runnable接口实现 。还是直接来看例子:
class compute implements Runnable {
int i = 0;
publicvoidrun() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
class compute1 implements Runnable {
publicvoidrun() {
for (int i = 0; i < 10; i++) {
System.out.println("这个数字是:" + i);
}
}
}
publicclassthreadtest {publicstaticvoidmain(String[] args) {
compute c = new compute();
compute1 c1 = new compute1();
Thread t = new Thread(c);
Thread t1 = new Thread(c1);
t.start();
t1.start();
}
}