线程优先级
线程优先级
- java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
- 线程的优先级用数字表示,范围从1-10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.MORM_PRIORITY = 5;
- 使用以下方法改变或获取优先级
- getPriority() //获取优先级
- setPriority(int XXX) //修改优先级
虽然线程的优先级越高,按照道理来说越先执行,但真正执行哪个线程还是由cpu调度决定。
package com.Luoking.Thread;
public class ThreadPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"优先级为-->"+Thread.currentThread().getPriority());
}
public static void main(String[] args) {
//主线程的默认线程
System.out.println(Thread.currentThread().getName()+"优先级为-->"+Thread.currentThread().getPriority());
ThreadPriority Priority = new ThreadPriority();
Thread T1 = new Thread(Priority,"T1");
Thread T2 = new Thread(Priority,"T2");
Thread T3 = new Thread(Priority,"T3");
Thread T4 = new Thread(Priority,"T4");
Thread T5 = new Thread(Priority,"T5");
//线程默认优先级
T1.start();
//设置优先级
T2.setPriority(2);
T2.start();
T3.setPriority(6);
T3.start();
T4.setPriority(8);
T4.start();
T5.setPriority(Thread.MAX_PRIORITY);
T5.start();
}
}
输出结果
main优先级为-->5
T5优先级为-->10
T4优先级为-->8
T1优先级为-->5
T2优先级为-->2
T3优先级为-->6
//可以看出,优先级越高,不一定越早执行