多线程-线程优先级(先设置优先级-再启动线程)


java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度那个线程来执行

线程的优先级用数字表示,范围从1-10

Thread.MIN_PRIORITY=1

Thread.MAX_PRIORITY=10

Thread.NORM_PRIORITY=5

使用以下方式改变或获取优先级

getPriority();setPriority(int xxx);
import java.util.Scanner;
//测试线程的优先级
public class Main {
    public static void main(String[] args) {
        //获取主线程优先级
     System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
    
        MyPriority mypriority=new MyPriority();
        //创建多个线程
        Thread thread1=new Thread(mypriority);
        Thread thread2=new Thread(mypriority);
        Thread thread3=new Thread(mypriority);
        Thread thread4=new Thread(mypriority);
        //一定要先设置线程的优先级,然后再启动,正常情况下,优先级高的线程会先执行,但是具体情况要看cpu的调用
        thread1.setPriority(1);
        thread1.start();
        
        thread2.setPriority(10);
        thread2.start();
        
        thread3.setPriority(3);
        thread3.start();
        
        thread4.setPriority(8);
        thread4.start();
    }
}

class MyPriority implements Runnable{
    public void run(){
    //获取线程名字,及线程优先级
    System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
        
        
    }
}

相关