【介绍】
线程的优先级就是线程获得CPU的概率,优先级越高,获取CPU的概率越大;从小到大,1-10之间,10是优先级最高,默认的优先级是5;
【设置优先级】
通过线程的setPriority设置线程的优先级;通过线程的getPriority获取线程的优先级,设置优先级需要在start之前设置;
class Panda{
public static void main(String[] args) {
//设置线程的优先级
//实现Runnable接口
Runnable runnable = new Runnable() {
@SneakyThrows
@Override
public void run() {
while(true){
//死循环,3秒打印一次
Thread.sleep(3000);
System.out.println("线程1");
}
}
};
//创建Thread类对象
Thread thread = new Thread(runnable);
//先获取线程的优先级
int priority = thread.getPriority();
//设置线程的优先级最高【必须在start()方法之前设置】
thread.setPriority(10);
//调用start() 方法执行线程
thread.start();
Thread thread1 = new Thread(new Runnable(){
@SneakyThrows
@Override
public void run() {
while(true){
//死循环,3秒打印一次
Thread.sleep(3000);
System.out.println("线程2");
}
}
});
//设置线程的优先级最低 1
thread.setPriority(1);
//执行线程
thread1.start();
}
}



