多线程---线程优先级

线程优先级

 

 

package com.mokuiran.thread;

//测试线程的优先级
//注意:优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度
//优先级高的并不一定就先执行,需要看CPU的调度
public class TestPriority {
   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);
       Thread thread5 = new Thread(myPriority);

       //先设置优先级,再启动
       thread1.start();//默认为5

       thread2.setPriority(1);
       thread2.start();

       thread3.setPriority(4);
       thread3.start();

       thread4.setPriority(Thread.MAX_PRIORITY);//MIN_PRIORITY=10
       thread4.start();

       thread5.setPriority(8);
       thread5.start();

  }
}
class MyPriority implements Runnable{

   @Override
   public void run() {
       try {
           Thread.sleep(1000);//设置延时,可以让优先级高的先执行的概率增加
      } catch (InterruptedException e) {
           e.printStackTrace();
      }
       System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
  }
}
 
posted @ 2022-09-17 13:46  默夔然  阅读(52)  评论(0)    收藏  举报