Java 实例 - 线程优先级设置

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

SimplePriorities.java 文件

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

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

  1. Thread[Thread-1,1,main]: 5
  2. Thread[Thread-2,1,main]: 5
  3. Thread[Thread-3,1,main]: 5
  4. Thread[Thread-0,10,main]: 5
  5. Thread[Thread-3,1,main]: 4
  6. Thread[Thread-0,10,main]: 4
  7. Thread[Thread-1,1,main]: 4
  8. Thread[Thread-5,1,main]: 5
  9. Thread[Thread-4,1,main]: 5
  10. Thread[Thread-2,1,main]: 4
  11. Thread[Thread-0,10,main]: 3
  12. Thread[Thread-1,1,main]: 3
  13. Thread[Thread-4,1,main]: 4
  14. Thread[Thread-2,1,main]: 3
  15. ……