线程的优先级案例讲解

线程优先级意义

线程的优先级告诉程序该线程的重要程度有多大。如果有大量线程都被堵塞,都在等候运行,程序会尽可能地先运行优先级的那个线程。 但是,这并不表示优先级较低的线程不会运行。若线程的优先级较低,只不过表示它被准许运行的机会小一些而已。

举例:就像车站买票 旁边会有牌子提示“军人优先”

就像并发运行时候,CPU分出小块时间片,线程优先级高的线程更容易获取时间片

线程优先级分类

线程的优先级设置可以为1-10的任一数值,Thread类中定义了三个线程优先级,分别是:MIN_PRIORITY(1)、NORM_PRIORITY(5)、MAX_PRIORITY(10),一般情况下推荐使用这几个常量,不要自行设置数值。

默认优先级5 最小1 最大10
在这里插入图片描述

在这里插入图片描述

默认优先级案例

/**
 * 线程优先级Demo
 */
public class PriorityDemo {

    public static void main(String [] args){
        Thread thread1 = new Thread(()->{
            while (true){
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程1");

        Thread thread2 = new Thread(()->{
            while (true){
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程2");

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

}

默认优先级下,每个线程都有可能先获取资源
在这里插入图片描述

设置线程优先级案例

public class PriorityDemo {

    public static void main(String [] args){
        Thread thread1 = new Thread(()->{
            while (true){
                System.out.println(Thread.currentThread().getName());

            }
        },"线程1");

        Thread thread2 = new Thread(()->{
            while (true){
                System.out.println(Thread.currentThread().getName());

            }
        },"线程2");

        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);

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

}

可以看到大部分输出线程2,线程1也是会获取到
在这里插入图片描述

不同平台,对线程的优先级的支持不同。 编程的时候,不要过度依赖线程优先级,如果你的程序运行是否正确取决于你设置的优先级是否按所设置的优先级运行,那这样的程序不正确

任务: 快速处理:设置高的优先级 慢慢处理:设置低的优先级

候,不要过度依赖线程优先级,如果你的程序运行是否正确取决于你设置的优先级是否按所设置的优先级运行,那这样的程序不正确**

任务: 快速处理:设置高的优先级 慢慢处理:设置低的优先级

猜你喜欢

转载自blog.csdn.net/q736317048/article/details/113801719