Java 实例 - 线程优先级设置

以下实例演示了如何通过setPriority() 方法来设置线程的优先级:

 1 SimplePriorities.java 文件
 2 public class SimplePriorities extends Thread {
 3    private int countDown = 5;
 4    private volatile double d = 0; 
 5    public SimplePriorities(int priority) {
 6       setPriority(priority);
 7       start();
 8    }
 9    public String toString() {
10       return super.toString() + ": " + countDown;
11    }
12    public void run() {
13       while(true) {
14          for(int i = 1; i < 100000; i++)
15          d = d + (Math.PI + Math.E) / (double)i;
16          System.out.println(this);
17          if(--countDown == 0) return;
18       }
19    }
20    public static void main(String[] args) {
21       new SimplePriorities(Thread.MAX_PRIORITY);
22       for(int i = 0; i < 5; i++)
23       new SimplePriorities(Thread.MIN_PRIORITY);
24    }
25 }

以上代码运行输出结果为:

Thread[Thread-1,1,main]: 5
Thread[Thread-2,1,main]: 5
Thread[Thread-3,1,main]: 5
Thread[Thread-0,10,main]: 5
Thread[Thread-3,1,main]: 4
Thread[Thread-0,10,main]: 4
Thread[Thread-1,1,main]: 4
Thread[Thread-5,1,main]: 5
Thread[Thread-4,1,main]: 5
Thread[Thread-2,1,main]: 4
Thread[Thread-0,10,main]: 3
Thread[Thread-1,1,main]: 3
Thread[Thread-4,1,main]: 4
Thread[Thread-2,1,main]: 3
……