线程的优先级
线程优先级:getPriority() setPriority(int x)
- Java提供了一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度那个线程来执行。
- 线程的优先级用数字来表示,范围1~10。
- Thread.MIN_PRIORITY = 1; 最小优先级
- Thread.MAX_PRIORITY = 10; 最大优先级
- Thread.NORM_PRIORITY = 5; 默认优先级(main方法)
- 使用一下方式改变或获取优先级
- getPriority()
- setPriority(int x)
- 优先级的设定建议在start()调度前
- 优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度。
Code
// 线程方法体
public class ThreadDemo implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
public class PriorityTest {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+ "-->" + Thread.currentThread().getPriority()); // Thread.currentThread().getPriority() 优先级name
ThreadDemo thread = new ThreadDemo();
Thread thread1 = new Thread(thread);
Thread thread2 = new Thread(thread);
Thread thread3 = new Thread(thread);
Thread thread4 = new Thread(thread);
Thread thread5 = new Thread(thread);
Thread thread6 = new Thread(thread);
thread1.start();
thread2.setPriority(2); // 设置优先级
thread2.start();
thread3.setPriority(Thread.MAX_PRIORITY); // 最大优先级
thread3.start();
thread4.setPriority(Thread.MIN_PRIORITY); // 最小优先级
thread4.start();
thread5.setPriority(9);
thread5.start();
thread6.setPriority(7);
thread6.start();
}
}
总结:可以看到尽管设置了优先级,但是依然有优先级低的线程在优先级高的线程前面执行,所以优先级低只是意味着获得调度的概率低并不是优先级低就不会被调用,这都是看CPU的调度。