线程优先级:
- Java提供了一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
- 线程的优先级用数字表示,范围从1~10.
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRORITY = 10;
- Thread.NORM_PRIORITY = 5;
- 使用以下方式改变或获取优先级
- getPriority() setPriority(int xxx)
1 package com.thread.state; 2 3 //测试线程优先级 4 public class TestPriority { 5 6 public static void main(String[] args) { 7 8 //主线程默认优先级 9 System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority()); 10 11 MyPriority myPriority = new MyPriority(); 12 13 Thread t1 = new Thread(myPriority); 14 Thread t2 = new Thread(myPriority); 15 Thread t3 = new Thread(myPriority); 16 Thread t4 = new Thread(myPriority); 17 Thread t5 = new Thread(myPriority); 18 Thread t6 = new Thread(myPriority); 19 20 //先设置优先级,再启动 21 t1.start(); 22 23 t2.setPriority(1); 24 t2.start(); 25 26 t3.setPriority(4); 27 t3.start(); 28 29 t4.setPriority(Thread.MAX_PRIORITY);//10 30 t4.start(); 31 32 33 } 34 } 35 36 class MyPriority implements Runnable { 37 38 @Override 39 public void run() { 40 System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority()); 41 } 42 } 43 44 结果: 45 main-->5 46 Thread-0-->5 47 Thread-1-->1 48 Thread-3-->10 49 Thread-2-->4
注意:
- 优先级低之是意味着获得调度的概率低,并不是优先级低就不会被调用了。这都是看cpu的调度。但也有可能会性能低的比性能高的先执行,引起性能倒置这个问题,但一般不会。
- 优先级的设定在start调度之前