[Java] java 线程优先级 →→→→→进入此内容的聊天室

来自 , 2020-04-02, 写在 Java, 查看 102 次.
URL http://www.code666.cn/view/45645a27
  1. public class Priority {
  2.        
  3.         static class MyThread extends Thread{
  4.                 private int ID = 0;
  5.                 public MyThread(int id){
  6.                         this.ID = id;
  7.                 }
  8.                 public void run(){
  9.                         System.out.println("MyThread-" + this.ID +
  10.                                         " begin! Priority: " + this.getPriority());
  11.  
  12.                         System.out.println("MyThread-" + this.ID + " end!");
  13.                 }
  14.         }
  15.  
  16.         public static void main(String[] args) {
  17.                 //建立3个优先级不同的线程
  18.                 MyThread[] myThreads = new MyThread[3];
  19.                 for (int i=0; i<3; i++){
  20.                         myThreads[i] = new MyThread(i+1);
  21.                         //三个线程的优先级分别是1,4,7
  22.                         myThreads[i].setPriority(i*3+1);
  23.                 }
  24.                 //按优先级从低到高启动线程
  25.                 for (int i=0; i<3; i++){
  26.                         myThreads[i].start();
  27.                 }
  28.                 //先启动的线程不一定先运行,虚拟机会考虑线程的优先级,同等情况下,优先级高的线程先运行
  29.         }
  30. }
  31.  

回复 "java 线程优先级"

这儿你可以回复上面这条便签

captcha