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资源的概率较大,优先级低的并非没机会执行。