1.线程的优先级
线程的优先级是指:线程的优先级越高,越有可能先执行,但仅仅是有可能而已。
在Thread类中有以下优先级方法:
- 设置优先级
public final void setPriority(int newPriority)
- 取得优先级
public int getPriority()
对于优先级的设定可以由Thread类的几个常量来决定
- 高优先级:public final static int MAX_PRIORITY = 10;
- 中等优先级:public final static int NORM_PRIORITY = 5;
- 低优先级:public final static int MIN_PRIORITY = 1;
观察主线程的优先级:
public class ThreadPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getPriority());
}
}
主线程只是一个中等优先级。
此外,线程是具有继承关系的,比如A线程中启动B线程,那么B和A的线程优先级是一样的。
2.守护线程
守护线程是一种特殊的线程,它属于一种陪伴线程。
Java中有俩种线程:用户线程和守护线程。
可以通过isDemon()方法来区别它们:如果返回false,则说明该线程是“用户线程”,否则就是“守护线程”。
典型的守护线程就是垃圾回收线程。
只要JVM进程中存在任何一个非守护线程没有结束,守护线程就在工作;只有当最后一个非守护线程结束时,守护线程才会随着JVM一起停止工作。
小tip:主线程main是用户进程
观察守护线程:
package mythread;
class A implements Runnable{
private int i ;
@Override
public void run() {
try {
while (true){
i++;
System.out.println("线程名称:"+Thread.currentThread().getName()+
"i=" +i+",是否为守护线程:"+Thread.currentThread().isDaemon());
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("线程名称"+Thread.currentThread().getName()+"中断线程了。。。");
}
}
}
public class TestDaemon {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new A(),"子线程A");
//设置线程A为守护线程,此语句必须在start方法之前执行
thread1.setDaemon(true);
thread1.start();
Thread thread2 = new Thread(new A(),"子线程B");
thread2.start();
Thread.sleep(3000);
//中断非守护线程
thread2.interrupt();
Thread.sleep(1000);
System.out.println("代码结束");
}
}
观察可知:B是用户线程,当它中断了之后守护线程并没有结束,是因为主线程(用户线程)还没有结束,说明所有用户线程全部结束之后,守护线程才会结束。