标签:
1 package com.xt.thinks21_2; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 /** 7 * java线程优先级测试 8 * 9 * @author Administrator 10 * 11 */ 12 public class ThreadPriorityTest implements Runnable { 13 private int countDown = 5; 14 private int priority; 15 private volatile double d; 16 17 public ThreadPriorityTest(int priority) { 18 this.priority = priority; 19 } 20 21 @Override 22 public String toString() { 23 // TODO Auto-generated method stub 24 return Thread.currentThread() + ":" + countDown; 25 } 26 27 @Override 28 public void run() { 29 // TODO Auto-generated method stub 30 Thread.currentThread().setPriority(priority); 31 while (true) { 32 for (int i = 0; i < 10000000; i++) { 33 d += (Math.PI + Math.E) / (double) i; 34 if (i % 1000 == 0) 35 Thread.yield(); 36 } 37 System.out.println(this); 38 if (--countDown == 0) 39 return; 40 } 41 } 42 43 public static void main(String[] args) { 44 ExecutorService es = Executors.newCachedThreadPool(); 45 for (int i = 0; i < 5; i++) 46 es.execute(new ThreadPriorityTest(Thread.MIN_PRIORITY)); 47 es.execute(new ThreadPriorityTest(Thread.MAX_PRIORITY)); 48 es.shutdown(); 49 } 50 }
线程内部执行耗时操作的时候,设置线程优先级可以有效的调整线程执行顺序(无规律)。
标签:
原文地址:http://www.cnblogs.com/wubingshenyin/p/4445830.html