Java 线程的优先级与守护线程

1.线程的优先级
线程的优先级是指:线程的优先级越高,越有可能先执行,但仅仅是有可能而已。
在Thread类中有以下优先级方法:

  • 设置优先级
public final void setPriority(int newPriority)
  • 取得优先级
public int  getPriority()

对于优先级的设定可以由Thread类的几个常量来决定

  1. 高优先级:public final static int MAX_PRIORITY = 10;
  2. 中等优先级:public final static int NORM_PRIORITY = 5;
  3. 低优先级: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是用户线程,当它中断了之后守护线程并没有结束,是因为主线程(用户线程)还没有结束,说明所有用户线程全部结束之后,守护线程才会结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值