java线程:线程的优先级

线程的优先级

  • Java为线程类提供了10个优先级
  • 优先级可以用整数1-10表示,超过范围会抛出异常
  • 主线程默认优先级为5
  • 优先级常量
    • MAX_ PRIORITY :线程的最高优先级10
    • MIN_ PRIORITY :线程的最低先级1
    • NORM_ PRIORITY :线程的默认优先级5
  • 优先级相关的方法
public int getPriority()       //获取线程优先级的方法
public void setPriority(int newPriority)     //设置线程优先级的方法

代码实现:

package java_thread;

class MyThread3 extends Thread{
    private String name;
    public MyThread3(String name){
        this.name = name;
    }

    public void run(){
        for(int i=0; i<10;i++){
            System.out.println(name + "正在运行" + i);
        }
    }
}

public class PriorityDemo {
    public static void main(String[] args) {
        //获取主线程的优先级
        int mainPriority = Thread.currentThread().getPriority();
        System.out.println("主线程的优先级为:" + mainPriority);

        MyThread3 mt1 = new MyThread3("线程1");
        mt1.setPriority(Thread.MAX_PRIORITY);     //等价于mt1.setPriority(10);
        System.out.println("线程1的优先级为:" + mt1.getPriority());
        mt1.start();
    }
}

输出:

主线程的优先级为:5
线程1的优先级为:10
线程1正在运行0
线程1正在运行1
线程1正在运行2
线程1正在运行3
线程1正在运行4
线程1正在运行5
线程1正在运行6
线程1正在运行7
线程1正在运行8
线程1正在运行9

若实例化两个线程:

public static void main(String[] args) {
    //获取主线程的优先级
    int mainPriority = Thread.currentThread().getPriority();
    // System.out.println("主线程的优先级为:" + mainPriority);

    MyThread3 mt1 = new MyThread3("线程1");
    MyThread3 mt2 = new MyThread3("线程2");
    mt1.setPriority(Thread.MAX_PRIORITY);   //等价于mt1.setPriority(10);
    mt2.setPriority(Thread.MIN_PRIORITY);
    System.out.println("线程1的优先级为:" + mt1.getPriority());
    System.out.println("线程2的优先级为:" + mt2.getPriority());
    mt1.start();
    mt2.start();
}

输出:

线程1的优先级为:10
线程2的优先级为:1
线程1正在运行0
线程1正在运行1
线程2正在运行0
线程1正在运行2
线程1正在运行3
线程2正在运行1
线程2正在运行2
线程1正在运行4
线程2正在运行3
线程2正在运行4
线程1正在运行5
线程2正在运行5
线程1正在运行6
线程2正在运行6
线程2正在运行7
线程1正在运行7
线程2正在运行8
线程1正在运行8
线程2正在运行9
线程1正在运行9

由结果可知:并不是优先级高的线程先执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值