一、介绍
在Java中,每一个线程都有一个优先级,默认是一个线程继承它的父线程的优先级。一个线程的默认优先级为NORM_PRIORITY = 5
设置优先级的方法setPriority() ,可设置的值如下:
1 2 3 | static int MAX_PRIORITY = 10;//线程可以具有的最高优先级(执行概率最高)static int MIN_PRIORITY = 1; //线程可以具有的最低优先级(执行概率最低)static int NORM_PRIORITY = 5;//分配给线程的默认优先级 |
线程的优先级:不是说哪个线程优先执行,如果设置某个线程的优先级高。那就是有可能被执行的概率高。并不是优先执行
二、实例
线程优先级实例代码:这里设置线程1为最高优先级(被执行的概率高) 设置线程2为最低优先级
这里设置了线程1最高和线程2最低优先级后,并不是说线程1就优先执行等到线程1执行完才执行线程2。而是说线程1被执行的概率高。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //线程类public class PriorityThread implements Runnable{ private boolean flag = true; private int num=0; @Override public void run() { while(flag){ System.out.println(Thread.currentThread().getName()+"-->"+num++); } } public void stop(){ this.flag = !this.flag; }}//测试线程优先级public class PriorityDemo { public static void main(String[] args) throws InterruptedException { PriorityThread it1 = new PriorityThread(); PriorityThread it2 = new PriorityThread(); Thread proxy1 = new Thread(it1,"线程1"); Thread proxy2 = new Thread(it2,"线程2"); proxy1.setPriority(Thread.MAX_PRIORITY);//设置为最高优先级 proxy2.setPriority(Thread.MIN_PRIORITY);//设置为最低优先级 proxy1.start(); proxy2.start(); Thread.sleep(1000); it1.stop(); it2.stop(); }} |
执行结果如下:
线程1-->47755 统计共执行了4685次
线程2-->19211 统计共执行了1469次
三、总结
1、每个线程都有一个默认的优先级,默认情况下是NORM_PRIORITY = 5
2、线程的优先级表示的是被执行的概率,并不是绝对的优先执行。
3、设置线程优先级的方法setPriority(Thread.MAX_PRIORITY);