java多线程之线程的优先级
在操作系统中,线程可以划分优先级,优先级较高的线程得到CPU资源较多,也就是CPU优先执行优先级较高的线程对象中的任务(其实并不是这样)。
在java中,线程的优先级用setPriority()方法就行,线程的优先级分为1-10这10个等级,如果小于1或大于10,则抛出异常throw new IllegalArgumentException(),默认是5。
- public class MyThread1 extends Thread {
- @Override
- public void run() {
- long startTime=System.currentTimeMillis();
- long addResult=0;
- for (int i = 0; i < 1000000; i++) {
- new Random().nextInt();
- addResult+=i;
- }
- long endTime=System.currentTimeMillis();
- System.out.println("thread1 use time--->"+(endTime-startTime));
- }
- }
- public class MyThread2 extends Thread {
- @Override
- public void run() {
- long startTime=System.currentTimeMillis();
- long addResult=0;
- for (int i = 0; i < 1000000; i++) {
- new Random().nextInt();
- addResult+=i;
- }
- long endTime=System.currentTimeMillis();
- System.out.println("thread2 use time--->"+(endTime-startTime));
- }
- }
- public class MyThread{
- public static void main(String[] args){
- for (int i = 0; i < 5; i++) {
- MyThread1 t1=new MyThread1();
- t1.setPriority(10);
- t1.start();
- MyThread2 t2=new MyThread2();
- t2.setPriority(1);
- t2.start();
- }
- }
- }
从结果中可以发现,也有thread2比thread1先执行完,也就验证了线程的优先级于代码执行顺序无关。
- public class MyThread{
- public static void main(String[] args){
- for (int i = 0; i < 5; i++) {
- MyThread1 t1=new MyThread1();
- t1.setPriority(6);
- t1.start();
- MyThread2 t2=new MyThread2();
- t2.setPriority(5);
- t2.start();
- }
- }
如果我们把优先级设置近点的话,发现优先级较高的线程不一定没一次都执行完,线程的优先级与打印的顺序无关,不要将这两点的关系相关联,他们的关系是不确定性和随机性。
线程的优先级仍然无法保障线程的执行次序。只不过,优先级高的线程获取CPU资源的概率较大,优先级低的并非没机会执行。
争议性
评论:
你的解释是错的,哥们。参见这里:http://bbs.****.net/topics/390502387
这个原因并不是优先级失效了,而是因为你的处理器是多核的。
这段代码在单核CPU上一定是先B1后B2的,但是现在处理器都是多核的,多核CPU是可以真正实现多个线程同时运行的,而不是简单的快速切换的假象,每个核心都能够负责一个线程。
你可以把你的CPU核心关掉一些,只留下一个核心工作,再运行这个。
关闭多核CPU核心的方法:
开始,运行,输入:MSCONFIG再点 BOOT.INI 找到高级选项,点开 /NUMPROC9(N)= 里面只选1就关掉另外的核了,如果你是四核,里面有1 2 3 4可选,点2就是只能当双核用,以此类推。