线程的优先级
-
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
-
线程的优先级用数字表示,范围从1~10
- Thread.MIN_PRIORITY=1
- Thread.MAX_PRIORITY=10
- Thread.NORM_PRIORITY=5
-
使用以下方式获得和改变线程的优先级
- getPriority()
- setPriority(int xxx)
-
优先级高代表抢到CPU时间片的概率大,不一定先执行,我们设置优先级,仅能作为参考,无法决定线程最终执行的顺序
package com.example.demo.testthread;
public class TestPriority implements Runnable {
public static void main(String[] args) {
TestPriority testPriority = new TestPriority();
Thread t1 = new Thread(testPriority, "线程1");
t1.start();
Thread t2 = new Thread(testPriority, "线程2");
t2.setPriority(Thread.MIN_PRIORITY);
t2.start();
Thread t3 = new Thread(testPriority, "线程3");
t3.setPriority(Thread.MAX_PRIORITY);
t3.start();
Thread t4 = new Thread(testPriority, "线程4");
t4.setPriority(8);
t4.start();
Thread t5 = new Thread(testPriority, "线程5");
t5.setPriority(Thread.NORM_PRIORITY);
t5.start();
System.out.println(Thread.currentThread().getName()+"执行,权重为"+Thread.currentThread().getPriority());
/*
优先级高代表抢到CPU时间片的概率大,不一定先执行,我们设置优先级,仅能作为参考,无法决定线程最终执行的顺序
输出:
线程3执行,权重为10
main执行,权重为5
线程1执行,权重为5
线程4执行,权重为8
线程5执行,权重为5
线程2执行,权重为1
*/
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行,权重为"+Thread.currentThread().getPriority());
}
}