setPriority 方法

setPriority 方法 能够给线程设置优先级, 优先级最高为10,最低为1。优先级越高,越有可能优先执行,但线程执行顺序仍具有不确定性,并不能保证优先级高的一定先执行。

我们编写了一个 Join 类,还是用来输出数字0-9。

public class Priority implements  Runnable{

    //线程的启动需要重写 run 方法
    @Override
    public void run(){
         
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"线程正在执行"+"第"+i+"次for循环");
        }
    }
}

我们编写了一个测试类 PriorityThreadDemo, 设置 线程 t1 优先级为1,也可以用 常量 Thread.MIN_PRIORITY 来表示,设置 线程 t2 优先级为10,也可以用 常量 Thread.MAX_PRIORITY 来表示。

public class PriorityThreadDemo {

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

        Priority  pt =new Priority ();

        Thread t1= new Thread(pt,"thread 1");
        t1.setPriority(1);
        t1.setPriority(Thread.MIN_PRIORITY);//和上一句等价

        Thread t2= new Thread(pt,"thread 2");
        t2.setPriority(Thread.MAX_PRIORITY );//和上一句等价

        t1.start();
        t2.start();

        //优先级设置后,运行的顺序并不绝对,依然由操作系统决定

    }
}

运行结果:

主线程的优先级为:5
t2线程正在执行第0次for循环
t2线程正在执行第1次for循环
t2线程正在执行第2次for循环
t2线程正在执行第3次for循环
t2线程正在执行第4次for循环
t2线程正在执行第5次for循环
t2线程正在执行第6次for循环
t1线程正在执行第0次for循环
t2线程正在执行第7次for循环
t1线程正在执行第1次for循环
t2线程正在执行第8次for循环
t2线程正在执行第9次for循环
t1线程正在执行第2次for循环
t1线程正在执行第3次for循环
t1线程正在执行第4次for循环
t1线程正在执行第5次for循环
t1线程正在执行第6次for循环
t1线程正在执行第7次for循环
t1线程正在执行第8次for循环
t1线程正在执行第9次for循环

可以看出,虽然我们设置了 t2 的优先级为最高10, t1 的优先级 为最低1,但是实际执行过程中并不能保证 t2 线程一定优先于 t1 线程的,只能说 t2 执行比较有可能 抢占 t1 的机会。

Last updated