Thread类提供了设置线程优先级的方法,为thread.setPriority()方法,其源代码如下:
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); } }
在Java里,线程的优先级分为1-10这10个等级,如果不在此范围内,则JDK抛出IllegalArgumentException。
三个优先级常量:
/** * 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;
优先级具有继承性,如果A线程启动了B线程,则B的优先级和A一样。
优先级具有规则性和随机性,JVM优先执行优先级高的线程对象中的任务,但这并不是绝对的。