这是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());
}
打印输出的结果是5和main
现在我自己创建5个线程,并分别给每个线程设置最小线程优先级:
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()); }
}
按照上面这个代码,我给每个自定义的线程设置优先级为1,应该是等主线程,MAIN执行完之后才执行另外5个自定义线程。
也就是先要打印构造函数里面的值,才开始执行run,但是为什么输出的结果是一下这个样子:
Making 1
Test1:Thread-1
Test1:1
Making 2
Test2:Thread-2
Test2:1
Making 3
Test3:Thread-3
Thread 2(5)
Thread 1(5)
Thread 2(4)
Test3:1
Thread 1(4)
Thread 2(3)
Thread 2(2)
Thread 2(1)
Making 4
Test4:Thread-4
Test4:1
Thread 1(3)
Thread 3(5)
Thread 4(5)
Making 5
Thread 3(4)
Thread 1(2)
Thread 4(4)
Test5:Thread-5
Thread 3(3)
Thread 1(1)
Thread 4(3)
Test5:1
Thread 3(2)
Thread 4(2)
Thread 3(1)
Thread 4(1)
All Threads Started
Thread 5(5)
5
Thread 5(4)
main
Thread 5(3)
Thread 5(2)
Thread 5(1)
是不是我对优先级理解错误啦。寻求真相。
问题补充
fmjsjx 写道
所谓线程优先级,个人理解只是对资源竞争的一个辨别依据,就是说当多个线程竞争资源时,具有较高优先级的线程会优先执行。
楼主的线程执行过程太短、逻辑太简单,基本不存在竞争问题,当然看不出优先级的作用……
其实所谓优先级只有在长期稳定运行的系统中才有用,这个很难测试的……
楼主的线程执行过程太短、逻辑太简单,基本不存在竞争问题,当然看不出优先级的作用……
其实所谓优先级只有在长期稳定运行的系统中才有用,这个很难测试的……
这样啊。