设置和获取线程优先级方法练习示例

int getPriority() 返回此线程的优先级。
public class MyThreadDemo {
    public static void main(String[] args) {
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        MyThread mt3 = new MyThread();

        mt1.setName("飞机");
        mt2.setName("高铁");
        mt3.setName("汽车");

       System.out.println(mt1.getPriority()); System.out.println(mt2.getPriority()); System.out.println(mt3.getPriority());
} }

运行结果可以得出,线程默认的优先级是:5

//void setPriority(int newPriority) 更改此线程的优先级。
把优先级设置成100时会发生异常:IllegalArgumentException,此异常 如果优先级不在 MIN_PRIORITYMAX_PRIORITY 时会发生,所以此时来获取这两个值的范围是多少
public static void main(String[] args) {
        System.out.println(Thread.MIN_PRIORITY);
        System.out.println(Thread.NORM_PRIORITY);
        System.out.println(Thread.MAX_PRIORITY);
    }

 最小值为:1 最大值为:10  默认值为:5

 
public class MyThreadDemo {
    public static void main(String[] args) {
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        MyThread mt3 = new MyThread();

        mt1.setName("飞机");
        mt2.setName("高铁");
        mt3.setName("汽车");


        //void setPriority(int newPriority) 更改此线程的优先级。
        mt1.setPriority(10);
        mt2.setPriority(5);
        mt3.setPriority(1);

        mt1.start();
        mt2.start();
        mt3.start();

    }
}
 
 
 

 经过多次调用,可以看出优先级高的有较大几率会优先运行

猜你喜欢

转载自www.cnblogs.com/pxy-1999/p/12788565.html