每个线程都有一个优先级。“高优先级线程”会优先于“低优先级线程”执行。每个线程都可以被标记为一个守护进程或非守护进程。在一些运行的主线程中创建新的子线程时,子线程的优先级被设置为等于“创建它的主线程的优先级”,当且仅当“创建它的主线程是守护线程”时“子线程才会是守护线程”。
每一个线程都被标记为“守护线程”或“用户线程”。当只有守护线程运行时,JVM会自动退出。
public class Thread1001{
static class Thread1002 extends Thread{
public Thread1002(String name){
super(name);
}
@Override
public void run() {
try{
for(int i=0;i<5;i++){
Thread.sleep(3);
System.out.println(this.getName() + " isDaemon(): " + this.isDaemon() + " loop: " + i);
}
} catch (InterruptedException e){
}
}
}
static class Thread1003 extends Thread{
public Thread1003(String name){
super(name);
}
@Override
public void run() {
try{
for(int i=0;i<1000;i++){
Thread.sleep(1);
System.out.println(this.getName() + " isDaemon(): " + this.isDaemon() + " loop: " + i);
}
} catch (InterruptedException e){
}
}
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " isDaemon: " + Thread.currentThread().isDaemon());
Thread t1 = new Thread1002("t1");
Thread t2 = new Thread1003("t2");
t2.setDaemon(true);
t1.start();
t2.start();
}
}
运行结果:
main isDaemon: false
t2 isDaemon(): true loop: 0
t2 isDaemon(): true loop: 1
t1 isDaemon(): false loop: 0
t2 isDaemon(): true loop: 2
t2 isDaemon(): true loop: 3
t1 isDaemon(): false loop: 1
t2 isDaemon(): true loop: 4
t2 isDaemon(): true loop: 5
t1 isDaemon(): false loop: 2
t2 isDaemon(): true loop: 6
t1 isDaemon(): false loop: 3
t2 isDaemon(): true loop: 7
t2 isDaemon(): true loop: 8
t1 isDaemon(): false loop: 4
t2 isDaemon(): true loop: 9
运行结果:
- 主线程main是用户线程,它创建的子线程t1也是用户线程。
- t2是守护线程。在“主线程main”和“子线程t1”(它们都是用户线程)执行完毕,只剩t2这个守护线程的时候,JVM自动退出。