多线程---线程优先级

线程优先级

 

 

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 @   默夔然  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示