程序猿学社的GitHub,欢迎Star
https://github.com/ITfqyd/cxyxs
本文已记录到github,形成对应专题。
前言
上一篇文章,我们了解线程安全的那些事,以及如何去解决线程安全的问题,本文就来聊一聊线程的优先级。
1.线程优先级的概念
- 通过查看Thread内的源码,我们可以知道线程优先级的取值范围为1-10,默认是5,值越大,表示抢到时间片的概念越高。但是,并不能保证一定能抢到。
- 如果没有在1-10之间,会抛出IllegalArgumentException异常
- 通过调用setPriority方法,设置线程的优先级(需要在就绪之前设置好)
案例: - 年会抽奖系统,我之前就听到朋友说过他们公司抽奖的事,通过抽奖名单可以发现,某一个项目组的开发人员中奖忒高。但是,那个小组还是有部分人员没有中奖,设置中奖概率高,不一定表示你100%能中奖。当然,针对这种行为,社长表示不赞同。
2.线程优先级小知识
子线程会使用父线程的优先级
public static void main(String[] args) {
System.out.println(Thread.currentThread().getPriority());
}
- getPriority方法获取线程的优先级
- 为什么是5? 如果我们没有指定某个线程的优先级,那这个线程的默认的优先级就是5。当然,这句话,也不是绝对的。下面这个demo,就可以推翻这个结论。
public static void main(String[] args) {
System.out.println("主线程优先级:"+Thread.currentThread().getPriority());
//1
Thread.currentThread().setPriority(1);
System.out.println("设置主线程的优先级为1");
Runnable runnable = new Runnable(){
@Override
public void run() {
System.out.println("程序猿学社:从线程优先级为"+Thread.currentThread().getPriority());
}
};
Thread thread = new Thread(runnable);
//2
//thread.setPriority(10);
thread.start();
}
1注释放开,2注释
- 线程的优先级默认为5,我们把主线程修改为1后,从线程的优先级也为1。因此,我们可以下结论。如果从线程优先级不指定的情况下,从现场优先级会跟主线程的优先级一样。
1注释放开,2注释放开
- 从线程已指定线程的优先级,会以从线程的优先级为准(就近原则)。
线程内使用线程
package com.cxyxs.thread.seven;
/**
* Description:
* 转发请注明来源 程序猿学社 - https://ithub.blog.csdn.net/
* Author: 程序猿学社
* Date: 2020/2/26 12:12
* Modified By:
*/
public class Demo2 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程优先级为"+Thread.currentThread().getPriority());
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程优先级为"+Thread.currentThread().getPriority());
}
};
Thread thread = new Thread(runnable,"隔壁老王");
//thread.setPriority(10);
thread.start();
}
public static void main(String[] args) {
Demo2 demo2 = new Demo2();
Thread thread = new Thread(demo2,"程序猿学社");
thread.setPriority(1);
thread.start();
}
}
- 如果被使用的线程没有指点优先级,以调用方线程为准。
- 被使用线程指定优先级,则以自身优先级为准(就近原则)。
线程优先级越高,是否优先执行?
package com.cxyxs.thread.seven;
/**
* Description:验证优先级高的是否优先执行
* 转发请注明来源 程序猿学社 - https://ithub.blog.csdn.net/
* Author: 程序猿学社
* Date: 2020/2/26 12:25
* Modified By:
*/
public class Demo3 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+","+i);
}
}
public static void main(String[] args) {
Demo3 demo = new Demo3();
Thread t = new Thread(demo,"程序猿学社");
Thread t1 = new Thread(demo,"后羿");
Thread t2 = new Thread(demo,"鲁班");
t.setPriority(1);
t2.setPriority(10);
t.start();
t1.start();
t2.start();
}
}
看测试的结果,是真的和符合我们之前提的问题,优先级高的线程先执行。
- 个人看法,不一定,优先级高,只是代表你抢到cpu时间片的概率高。例如,你学习成绩好,每次都是第一名,不意味着你每次考试都是N01。在实际上的开发过程中,暂时还没有用到这块。