- 线程可以有自己的优先级,优先级高的线程在竞争资源时会更有优势,但是这不是绝对的。
- Java线程优先级整型成员变量priority来标识,范围从1到10,数字越大优先级越高。其中有三个静态标量:
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
以下代码可以展示优先级高的线程倾向于更快完成:
package temp;
public class PriorityDemo {
public static class HighPriority extends Thread{
static int count = 0;
public void run() {
while(true) {
synchronized(PriorityDemo.class){
count++;
if(count > 10000000) {
System.out.println("HighPriority is complete!");
break;
}
}
}
}
}
public static class LowPriority extends Thread{
static int count = 0;
public void run() {
while(true) {
synchronized(PriorityDemo.class) {
count++;
if(count > 10000000) {
System.out.println("lowPriority is complete!");
break;
}
}
}
}
}
public static void main(String[] args) throws InterruptedException{
Thread high = new HighPriority();
LowPriority low = new LowPriority();
high.setPriority(Thread.MAX_PRIORITY);
low.setPriority(Thread.MIN_PRIORITY);
low.start();
high.start();
}
}