JAVA并发,线程优先级

 package com.xt.thinks21_2;

 import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* java线程优先级测试
*
* @author Administrator
*
*/
public class ThreadPriorityTest implements Runnable {
private int countDown = 5;
private int priority;
private volatile double d; public ThreadPriorityTest(int priority) {
this.priority = priority;
} @Override
public String toString() {
// TODO Auto-generated method stub
return Thread.currentThread() + ":" + countDown;
} @Override
public void run() {
// TODO Auto-generated method stub
Thread.currentThread().setPriority(priority);
while (true) {
for (int i = 0; i < 10000000; i++) {
d += (Math.PI + Math.E) / (double) i;
if (i % 1000 == 0)
Thread.yield();
}
System.out.println(this);
if (--countDown == 0)
return;
}
} public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++)
es.execute(new ThreadPriorityTest(Thread.MIN_PRIORITY));
es.execute(new ThreadPriorityTest(Thread.MAX_PRIORITY));
es.shutdown();
}
}

线程内部执行耗时操作的时候,设置线程优先级可以有效的调整线程执行顺序(无规律)。

上一篇:ThinkPHP的缓存 F方法


下一篇:Kaggle Competition Past Solutions