Java:线程的优先级


1:等级

  • MAX_PRIORITY:10
  • MIN _PRIORITY:1
  • NORM_PRIORITY:5 -->默认优先级

2:如何获取和设置当前线程的优先级:

  • getPriority():获取线程的优先级
  • setPriority(int p):设置线程的优先级

说明:高优先级的线程要抢占低优先级线程cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下被执行。并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行。

class HelloThread extends Thread{
    
    
    public HelloThread(String name) {
    
    
        super(name);
    }
    public HelloThread(){
    
    
    }
    @Override
    public void run(){
    
    
        System.out.println(Thread.currentThread().getName()+"正在执行");
    }
}

public class ThreadMethodTest {
    
    
    public static void main(String[] args) {
    
    
        //创建线程的时候设置名字,需要在子类中定义一个有参的构造方法并通过super调用父类有参的构造方法
        HelloThread helloThread = new HelloThread("分线程");
        //默认分线程和主线程的优先级都是5
        System.out.println(helloThread.getName()+"的优先级:"+helloThread.getPriority());
        System.out.println(Thread.currentThread().getName()+"的优先级:"+Thread.currentThread().getPriority());
        helloThread.setPriority(Thread.MAX_PRIORITY);
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        System.out.println("-----");
        //设置分线程和主线程的优先级
        System.out.println(helloThread.getName()+"的优先级:"+helloThread.getPriority());
        System.out.println(Thread.currentThread().getName()+"的优先级:"+Thread.currentThread().getPriority());

        helloThread.start();
        System.out.println(Thread.currentThread().getName()+"正在执行");
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_51755061/article/details/115087800