线程优先级(线程具有继承性、setPriority、getPriority)

什么 是线程优先级?
线程优先级是指优先级越高,越有可能先执行,但只是建议先执行,具体什么时候执行由系统决定。

设置线程优先级

  • public final void setPriority(int newPriority) ;

取得线程优先级

  • public final int getPriority( );

在Thread类中定义了三种静态成员变量:

  • public final static int MIN_PRIORITY = 1;
  • public final static int NORM_PRIORITY = 5;
  • public final static int MAX_PRIORITY = 10;

也就是线程优先级的取值范围是1-10;

我们知道主方法是一个JVM进程的主线程,那主线程的优先级是多少呢?

public class Prio
{
    public static void main(String[] args)
    {
        System.out.println(Thread.currentThread().getPriority());  //主线程优先级为5
    }
}

主线程的优先级只是一个普通优先级—>5。

有了优先级可以设置线程优先级,当多个线程并发执行时,将某个线程优先级设高,建议cpu先调度这个线程,但具体什么时候调度由系统决定。
代码如下:

class  Mythraed3 implements Runnable
{
    public  void run()
    {
        for(int i=0;i<3;i++)
        {
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
}

public class Prio
{
    public static void main(String[] args)
    {
        Mythraed3 thread=new Mythraed3();
        Thread thread1=new Thread(thread,"线程1");
        Thread thread2=new Thread(thread,"线程2");
        Thread thread3=new Thread(thread,"线程3");
        thread1.setPriority(2);
        thread2.setPriority(6);
        thread3.setPriority(Thread.MAX_PRIORITY); //将线程3优先级设置最高
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

**图片**

线程具有继承性

线程是有继承关系的,比如当A线程中启动B线程,那么B和A的优先级将是一样的。

线程具有继承性

class  Mythraed3 implements Runnable
{
    public  void run()
    {
        System.out.println(Thread.currentThread().getName()+"优先级为"+Thread.currentThread().getPriority());
        Thread thread=new Thread(new Mythraed4(),"线程2");
        thread.start(); //在线程1里启动线程2,线程2优先级和线程1优先级一样
    }
}
class Mythraed4 implements  Runnable
{
    public void run()
    {
        System.out.println(Thread.currentThread().getName()+"优先级为"+Thread.currentThread().getPriority());
    }
}
public class Prio
{
    public static void main(String[] args)
    {
        Mythraed3 thread=new Mythraed3();
        Thread thread1=new Thread(thread,"线程1");
        thread1.start();
        thread1.setPriority(3);
    }
}

在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值