优先级
Thread源代码:
/* The minimum priority that a thread can have.*/
public final static int MIN_PRIORITY = 1;/* The default priority that is assigned to a thread. */
public final static int NORM_PRIORITY = 5;/* The maximum priority that a thread can have.*/
public final static int MAX_PRIORITY = 10;
1,5,10,最小,默认,最大。
稍微注意的就是:可以在1-10之间取任意整数,但是不能大于10或小于1
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
红字的意思就是,参数大于最大优先级或是小于最小优先级,抛出无效参数异常。
并且在线程中创建的线程,默认优先级也是当前线程的优先级。
class Demo{
public static void main(String[] args){
PriorityThread thread=PriorityThread();
Thread t1=new Thread(thread);
t1.start();
}
}
class PriorityThread implements Runnable{
@override
public void run(){
System.out.println(Thread.currentThread().toString());
}
}
输出结果:
Thread[Thread-0,5,main]
Thread-0线程名称,5则是优先级,main是所属线程组
接下来看看main的优先级
class Demo{
public static void main(String[] args){
System.out.println("main : "+Thread.currentThread.getPriority());
}
}
输出结果:
main : 5
init()也写到
//code....
Thread parent = currentThread();
this.priority = parent.getPriority();