这是java线程的优先级:
java.lang.Thread
public static final int MAX_PRIORITY 10
public static final int MIN_PRIORITY 1
public static final int NORM_PRIORITY 5
默认main方法也就是主线程的级别是5,这个我测试过啦:
public static void main(String args []){
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader);
System.out.println(Thread.currentThread().getPriority());
System.out.println(Thread.currentThread().getName());
}
public class Test extends Thread{private int countDown = 5; private int threadNumber; private static int threadCount = 0; public Test() { threadNumber = ++threadCount; System.out.println("Making " + threadNumber); } public void run() { while(true) { System.out.println("Thread " + threadNumber + "(" + countDown + ")"); if(--countDown == 0) return; } } public static void main(String args []){ for(int i = 0; i < 5; i++){ Test test = new Test(); System.out.println("Test"+(i+1)+":"+test.getName()); test.setPriority(1); //设置为最小级别 System.out.println("Test"+(i+1)+":"+test.getPriority()); test.start(); } System.out.println("All Threads Started"); System.out.println(Thread.currentThread().getPriority()); System.out.println(Thread.currentThread().getName()); }
}
所谓线程优先级,个人理解只是对资源竞争的一个辨别依据,就是说当多个线程竞争资源时,具有较高优先级的线程会优先执行。
楼主的线程执行过程太短、逻辑太简单,基本不存在竞争问题,当然看不出优先级的作用……
其实所谓优先级只有在长期稳定运行的系统中才有用,这个很难测试的……
这个一般不要设哦,从程序逻辑上下手改吧,这个可控性不强。
优先级对JVM来说只是建议,最终怎么执行还是看JVM的.
线程优先级取决于操作系统最终对线程的调试,并不一定严格相同。