Java多线程之线程优先级

1、Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该先执行哪个线程

2、线程的优先级用数字表示,范围从1-10,如果超出此范围会报异常

    Thread.MIN_PRIORITY=1;Thread.MAX_PRIORITY=10;Thread.NORM_PRIORITY=5

3、使用以下方式获得或设置优先级

    getPriority() setPriority()

注意:优先级低只是意味着被cpu调度的概率低,并不是不会调用,优先级的设定建议在start()方法前

package lesson04;

public class TestPriority{


    public static void main(String[] args) {
        Thread t1 = new Thread (()->{

            System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
        });
        Thread t2 = new Thread (()->{

            System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
        });
        Thread t3 = new Thread (()->{

            System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
        });
        //输出主线程优先级

        t1.start();

        t2.setPriority(Thread.MAX_PRIORITY);
        t2.start();

        t3.setPriority(7);
        t3.start();




    }
}

 

你可能感兴趣的:(java,多线程,thread)