打字猴:1.700449993e+09
1700449993
1700449994 class TestThread implements Runnable{
1700449995
1700449996 //启动线程
1700449997
1700449998 public void start(int_priority){
1700449999
1700450000 Thread t=new Thread(this);
1700450001
1700450002 //设置线程优先级
1700450003
1700450004 t.setPriority(_priority);
1700450005
1700450006 t.start();
1700450007
1700450008 }
1700450009
1700450010 @Override
1700450011
1700450012 public void run(){
1700450013
1700450014 //消耗CPU的计算,性能差的机器,请修改循环限制
1700450015
1700450016 for(int i=0;i<100000;i++){
1700450017
1700450018 Math.hypot(Math.pow(924526789,i),Math.cos(i));
1700450019
1700450020 }
1700450021
1700450022 //输出线程优先级
1700450023
1700450024 System.out.println(“Priority:”+Thread.currentThread().getPriority());
1700450025
1700450026 }
1700450027
1700450028 }
1700450029
1700450030 该多线程类实现了Runnable接口,实现了run方法,注意在run方法中有一个比较占用CPU的计算,该计算毫无意义,只是为了保证一个线程尽可能多地消耗CPU资源,目的是为了观察CPU繁忙时不同优先级线程的执行顺序。需要说明的是,如果此处使用了Thread.sleep()方法,则不能体现出线程优先级的本质了,因为CPU并不繁忙,线程调度不会遵循优先级顺序来进行调度。
1700450031
1700450032 客户端的代码如下:
1700450033
1700450034 public static void main(String[]args){
1700450035
1700450036 //启动20个不同优先级的线程
1700450037
1700450038 for(int i=0;i<20;i++){
1700450039
1700450040 new TestThread().start(i%10+1);
1700450041
1700450042 }
[ 上一页 ]  [ :1.700449993e+09 ]  [ 下一页 ]