Java Thread Programming 1.6 - Thread Prioriti…
2008-02-23 09:36:20来源:互联网 阅读 ()
private volatile boolean stopRequest;
private boolean yield;
public PriorityYield(String name,int priority,boolean yield){
this.yield = yield;
this.counter = 0;
this.stopRequest = false;
Runnable r = new Runnable(){
public void run(){
try{
runwork();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
};
innerThread = new Thread(r,name);
innerThread.setPriority(priority);
}
/** 线程主体 */
public void runwork(){
Thread.yield();
while(!this.stopRequest){
if(this.yield){
Thread.yield();
}
counter ;
double x = 0;
for(int i = 0; i < 1000; i )//让线程处于活动状态,而不是sleep
x = Math.PI*i/Math.E;
}
}
/** 开始线程 */
public void startThread(){
this.innerThread.start();
}
/** 结束线程 */
public void stopThread(){
this.stopRequest = true;
}
public int getCounter(){
return this.counter;
}
/** 返回线程优先级和线程名 */
public String getPriorityandName(){
return "Thread:" innerThread.getName() "/Priority:" innerThread.getPriority();
}
public static void runMain(boolean yield){
/*定义三个线程*/
PriorityYield[] pys = new PriorityYield[3];
pys[0] = new PriorityYield("PY0",3,yield);
pys[1] = new PriorityYield("PY1",6,yield);
pys[2] = new PriorityYield("PY2",6,yield);
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
/*启动三线程*/
for(int i = 0 ; i < pys.length; i ){
pys[i].startThread();
}
long startTime = System.currentTimeMillis();
/*让线程运行一段时间*/
try{
Thread.sleep(10000);
}catch(InterruptedException e){}
/*停止线程运行*/
for(int i = 0; i < pys.length; i ){
pys[i].stopThread();
}
long stopTime = System.currentTimeMillis();
/*等线程完全停止运行*/
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
/*获得三线程总计数*/
int totalCounter = 0;
for(int i = 0; i < pys.length; i ){
totalCounter = pys[i].getCounter();
}
/*输出统计结果*/
System.out.println("totalcount=" totalCounter " counter/ms=" totalCounter/(stopTime - startTime));
for(int i = 0; i < pys.length; i ){
System.out.println(pys[i].getPriorityandName() ", count=" pys[i].counter " ," pys[i].counter*100/totalCounter "%");
}
}
public static void main(String[] args) {
Runnable r =new Runnable(){
public void run(){
System.out.println("run without yield");
runMain(false);//不使用yield
System.out.println();
System.out.println("run with yield");
runMain(true);//使用yield
}
};
Thread t = new Thread(r,"PriorityYield");
t.setPriority(Thread.MAX_PRIORITY - 1);
t.start();
}
}
输出结果:
run without yield
totalcount=454665 counter/ms=45
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有