首页  >  文章  >  Java  >  Java 实例 - 线程优先级设置

Java 实例 - 线程优先级设置

黄舟
黄舟原创
2016-12-27 13:29:571548浏览

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

/*
 author by w3cschool.cc
 SimplePriorities.java
 */public class SimplePriorities extends Thread {
   private int countDown = 5;
   private volatile double d = 0; 
   public SimplePriorities(int priority) {
      setPriority(priority);
      start();
   }
   public String toString() {
      return super.toString() + ": " + countDown;
   }
   public void run() {
      while(true) {
         for(int i = 1; i < 100000; i++)
         d = d + (Math.PI + Math.E) / (double)i;
         System.out.println(this);
         if(--countDown == 0) return;
      }
   }
   public static void main(String[] args) {
      new SimplePriorities(Thread.MAX_PRIORITY);
      for(int i = 0; i < 5; i++)
      new SimplePriorities(Thread.MIN_PRIORITY);
   }}

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

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
……

 以上就是Java 实例 - 线程优先级设置的内容,更多相关内容请关注PHP中文网(www.php.cn)!


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn