在网上搜索“线程的优先级在什么时候设置,在任何时候都能设置吗?”之类的问题,得到的答案基本都说:
线程开始(start)之前,仔细想想好像也合理,但是,实践是检验真理的唯一标准,在没有代码结果证明的情况下的这类答案是不可靠的
下面来验证一下:
先写个测试类
public class Test { public static void main(String[] args) { Runnable r=new Runnable() { int num=0; @Override public void run() { // TODO Auto-generated method stub //线程循环阻塞,没那么快死亡,方便验证结果 for(int i=0;i<100;i++) { num++; try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; Thread t=new Thread(r); //查看线程创建后默认的优先级值 System.out.println(t.getPriority()+"++++++++++"); System.out.println(t.getPriority()+"++++++++++"); //线程启动前设置线程的优先级值为7 t.setPriority(7); //线程启动前查看重新设置后线程的优先级值 System.out.println(t.getPriority()+"++++++++++1111"); System.out.println(t.getPriority()+"++++++++++1111"); //启动线程 t.start(); //线程启动后再次查看线程的优先级值 System.out.println(t.getPriority()+"++++++++++2222"); System.out.println(t.getPriority()+"++++++++++2222"); //线程启动后设置线程的优先级值为8 t.setPriority(8); System.out.println(t.getPriority()+"----------"); System.out.println(t.getPriority()+"----------"); //线程休息5s后重新设置线程优先级并查看优先级值 try { Thread.currentThread().sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t.setPriority(6); System.out.println(t.getPriority()+"**********"); System.out.println(t.getPriority()+"**********"); } }
输出结果为:
5++++++++++
5++++++++++
7++++++++++1111
7++++++++++1111
7++++++++++2222
7++++++++++2222
8----------
8----------
6**********
6**********