线程优先级

线程可以通过设置优先级来控制获得CPU的概率,注意这里只是概率,如果低优先级的线程很早到达,且能被分到CPU那么此时低优先的线程会比高优先级但后到来的线程更早运行
可以通过getPrioritysetPriority 来获取和设置线程的优先级

    /**
     * The minimum priority that a thread can have.
     */
    public static final int MIN_PRIORITY = 1;

    /**
     * The default priority that is assigned to a thread.
     */
    public static final int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public static final int MAX_PRIORITY = 10;

由官方文档不难看出,线程优先级的设置只能在[1, 10]之间,超过会抛出异常

public class ThreadPriority {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
        MyThread myThread = new MyThread();
        Thread thread1 = new Thread(myThread);
        Thread thread2 = new Thread(myThread);
        Thread thread3 = new Thread(myThread);
        Thread thread4 = new Thread(myThread);
        // 先设置优先级,再启动
        thread1.start();
        thread2.setPriority(1);
        thread2.start();
        thread3.setPriority(4);
        thread3.start();
        thread4.setPriority(Thread.MAX_PRIORITY);
        thread4.start();
    }
}

通过上面的程序我们可能会观测到线程优先级带来的变化,但是一定可以得到的是,线程的默认优先级是5,也就是NORM_PRIORITY

posted @ 2025-11-02 20:37  Huaixuxm  阅读(4)  评论(0)    收藏  举报