线程的优先级

线程的优先级

java可以查看和设置线程的优先级,优先级用数字表示,越大表示优先级越高,范围为整数1到10。

以下代码演示如何查看和设置优先级:

package com.cxf.multithread.priority;

public class TestForPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" priority is "+Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new TestForPriority());
        Thread thread2 = new Thread(new TestForPriority());
        Thread thread3 = new Thread(new TestForPriority());

        thread1.setPriority(4);
        thread2.setPriority(9);
        thread3.setPriority(10);

        System.out.println("main priority is "+Thread.currentThread().getPriority());

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

输出结果:

main priority is 5
Thread-0 priority is 4
Thread-1 priority is 9
Thread-2 priority is 10

setPriority方法设置优先级,getPriority方法查看优先级。

小规模的任务从运行结果体现不出来线程优先级。

posted on 2021-10-24 15:34  菜小疯  阅读(208)  评论(0编辑  收藏  举报