线程的优先级

线程的优先级

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

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

  • Thread.MIN_PRIONRITY = 1;

  • Thread.MAX_PRIORITY = 10;

  • Thread.NORMJ_PRIORITY = 5;

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

  • getPriority().srtPriority(int xxx)

 

优先级 地只是意味着获得调度的概率度,并不是优先级低的就不会被调用了,这都是看cpu的调度

package BufferedTest;

public class TestPriority extends Thread{
  public static void main(String[] args) {
      System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());//主线程默认优先级
      MyPriority p1 = new MyPriority();
      Thread t1= new Thread(p1);
      Thread t2= new Thread(p1);
      Thread t3 = new Thread(p1);
      Thread t4= new Thread(p1);
      Thread t5= new Thread(p1);

      t5.setPriority(2);
      t5.start();
      t4.setPriority(Thread.MAX_PRIORITY);//线程默认最高优先执行
      t4.start();
      t1.setPriority(9);
      t1.start();
  }

}
class MyPriority implements Runnable{

  @Override
  public void run() {
      System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());//当前线程的名字+优先级
  }
}
posted @ 2021-09-07 17:17  πππ·  阅读(57)  评论(0)    收藏  举报