线程的优先级指的是,线程的优先级越高越有可能先执行,但仅仅是有可能而已。
在Thread类中提供有如下优先级方法:
- 设置优先级
public final void setPriority(int newPriority)
- 获取优先级
public final 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 MyRunnable implements Runnable {
public void run() {
int i=3;
while(i>0){
System.out.println(Thread.currentThread().getName()+":"+i);
i--;
}
}
public static void main(String[] args) throws InterruptedException {
MyRunnable myThread=new MyRunnable();
Thread thread1=new Thread(myThread,"线程1");
Thread thread2=new Thread(myThread,"线程2");
Thread thread3=new Thread(myThread,"线程3");
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread3.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
thread3.start();
}
}
那么主方法也是一个线程,主方法的优先级是什么呢?
public static void main(String[] args) throws InterruptedException {
int a= Thread.currentThread().getPriority();
System.out.println(a);
}
线程具有继承性
比如在线程A中启动了线程B,那么线程A和线程B的优先级将是一样的,代码如下:
class A implements Runnable{
@Override
public void run() {
System.out.println("A的优先级是"+Thread.currentThread().getPriority());
Thread thread=new Thread(new B());
thread.start();
}
}
class B implements Runnable{
@Override
public void run() {
System.out.println("B的优先级是"+Thread.currentThread().getPriority());
}
}
public class Test3 {
public static void main(String[] args) {
Thread thread=new Thread(new A());
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
}
}
守护线程
守护线程是一种特殊的线程,它属于是一种陪伴线程。简单点说 java 中有两种线程:用户线程和守护线程。可以通过 isDaemon() 方法来区别它们:如果返回 false ,则说明该线程是“用户线程”;否则就是“守护线程”。典型的守护线程就是垃圾回收线程。只要当前JVM进程中存在任何一个非守护线程没有结束,守护线程就在工作;只有当最后一个非守护线程结束时,守护线程才会随着JVM一同停止工作。
注意:主线程main是用户线程。
public class MyRunnable implements Runnable {
private int i=1;
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 static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable=new MyRunnable();
Thread thread=new Thread(myRunnable,"线程A");
thread.setDaemon(true);
thread.start();
Thread thread1=new Thread(myRunnable,"线程B");
thread1.start();
Thread.sleep(3000);
thread1.interrupted();
Thread.sleep(1000);
System.out.println("程序结束");
}
}
结果表明,线程B中断后,线程A还没有结束,那是因为主线程还没有结束,所以 守护线程不会结束。说明
用户线程结束之后守护线程才会结束。