本文主要是介绍优先级的规律性——T1142,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package 多线程技能1;import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import org.w3c.dom.ls.LSOutput;import java.util.Random;/*** 优先级的规律性* 虽然使用setPriority()方法可以设置线程的优先级,但还没有看到设置优先级所带来的效果** 从运行结果来看,线程优先级高的总是大部分先执行完,但不代表高优先级的线程全部执行完。* 另外,并不是MyThread1线程被main线程调用就先执行完,出现这种结果的是因为MyThread1* 优先级是最高级别10.当线程优先级的等级差距很大时,谁先执行完和代码的调用顺序无关。** 从Run2的结果来看,大部分MyThread2先执行完,这就验证了线程的优先级与代码的调用顺序* 无关,出现这种结果的原因是因为MyThread2的优先级最高,说明线程的优先级具有一定的规律* 性,即CPU尽量将执行资源让给优先级较高的线程。**/
class MyThreadT1142 extends Thread{@Overridepublic void run() {long begTime=System.currentTimeMillis();long addResult=0;for (int j=0;j<10;j++){for (int i=0;i<50000;i++){Random random=new Random();random.nextInt();addResult=addResult+1;}}long endTime=System.currentTimeMillis();System.out.println("*****thread 1 use time="+(endTime-begTime));}
}
class MyThread2T1142 extends Thread{@Overridepublic void run() {long beginTime =System.currentTimeMillis();long addResult =0;for (int j=0;j<10;++j){for (int i=0;i<50000;++i){Random random=new Random();random.nextInt();addResult=addResult+i;}}long endTime =System.currentTimeMillis();System.out.println("-----Thread 2 use time="+(endTime-beginTime));}
}/*** 运行*/
class RunT1142{public RunT1142(){int h=5;for (int i=0;i<h;++i){MyThreadT1142 threadT1142=new MyThreadT1142();threadT1142.setPriority(10);threadT1142.start();MyThread2T1142 myThread2T1142=new MyThread2T1142();myThread2T1142.setPriority(1);myThread2T1142.start();}}
}
class Run2T1142{public Run2T1142(){int N=5;for (int i=0;i<N;++i){MyThreadT1142 myThreadT1142=new MyThreadT1142();myThreadT1142.setPriority(1);myThreadT1142.start();MyThread2T1142 myThread2T1142=new MyThread2T1142();myThread2T1142.setPriority(10);myThread2T1142.start();}}
}
public class T1142 {public static void main(String[] args) {// RunT1142 runT1142=new RunT1142();System.out.println("---------------------");Run2T1142 run2T1142=new Run2T1142();}
}
这篇关于优先级的规律性——T1142的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!