JAVA多线程优先级运行顺序的问题

先上代码
class myRunnable1 implements Runnable
{
public void run()
{
for(int i=0;i<50000;i++)
{
System.out.print("1");
}
}
}

class myRunnable2 implements Runnable
{
public void run()
{
for(int i=0;i<50000;i++)
{
System.out.print("2");
}
}
}

class myRunnable3 implements Runnable
{
public void run()
{
for(int i=0;i<50000;i++)
{
System.out.print("3");
}
}
}

class myRunnable4 implements Runnable
{
public void run()
{
for(int i=0;i<50000;i++)
{
System.out.print("4");
}
}
}

class myRunnable5 implements Runnable
{
public void run()
{
for(int i=0;i<50000;i++)
{
System.out.print("5");
}
}
}

class myRunnable6 implements Runnable
{
public void run()
{
for(int i=0;i<50000;i++)
{
System.out.print("6");
}
}
}

public class myRun
{
public static void main(String[] args)
{
myRunnable1 mr1=new myRunnable1();
myRunnable2 mr2=new myRunnable2();
myRunnable3 mr3=new myRunnable3();
myRunnable4 mr4=new myRunnable4();
myRunnable5 mr5=new myRunnable5();
myRunnable6 mr6=new myRunnable6();
Thread t1=new Thread(mr1);
Thread t2=new Thread(mr2);
Thread t3=new Thread(mr3);
Thread t4=new Thread(mr4);
Thread t5=new Thread(mr5);
Thread t6=new Thread(mr6);
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t4.setPriority(Thread.MAX_PRIORITY);
t5.setPriority(Thread.MAX_PRIORITY);
t6.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}

设置了优先级,6个线程运行的顺序是随机的。最开始我只写了2个线程,设置优先级,运行随机,我以为是4核CPU可以同时运行,所以不分优先级。后来我写了6个线程,也把运行次数提升到了50000次,前5个线程最高优先级,第六个最低优先级,但运行顺序还是随机的。求各位高手解释啊。。。

这个。。你不必纠结。。
深入说的话,其实。。很深。。
首先说 线程优先级,并不能保证优先级高的先运行,也不保证优先级高的更多的分配CPU时间,只是对系统的建议而已,到底运行哪个,是操作系统决定的,都不是java说了算的。
另外java只能保证在线程内部看起来是顺序执行你的代码的,并不能保证从其他线程看来这个是按照你编码顺序执行的。。追问

- -|||但至少几率应该大点儿吧。。。我运行了很多次。。。完全没发现有任何优先级体现出来啊。。。那优先级有啥意义呢?

追答

根据java语言规范,程序的正确性和性能保障,不能依靠优先级。
要靠程序自己控制。
优先级这个东西一般在系统资源紧缺的情况下可能会比较明显。
你这个经过运行时优化之后,几乎没有什么了。
所以体现不出来。

温馨提示:内容为网友见解,仅供参考
第1个回答  2012-12-15
优先级高不代表说一定是优先级最高的运行完了再让优先级地的运行。否则那样多线程就没意义了。
优先级高就是说同等条件下我运行的概率会比优先级低的高,至于具体怎么分配,这样看虚拟机的策略。但是肯定不会是像你想的那样,优先级高的运行完才运行优先级低的
第2个回答  2012-12-15
设置优先级只是让CPU选择优先级高的执行机会大一点,不代表必定执行的次数多,就像一个袋子有3个红球,2个蓝球,摸十次,并不代表红球摸到的次数多,只是说被摸到的机率大而已
相似回答