文
章
目
录
章
目
录
本文主要介绍如何设置Thread线程类的优先级。
线程优先级,顾名思义,就是优先级高的线程会优先获取CPU的使用权,但实际往往不是如此,它实际上也是一个提示操作,与yield一样,除了root用户或者CPU资源处于繁忙的情况下,设置优先级才有可能有效,所以不可过多的依赖优先级来处理具体的业务逻辑。
1、设置线程优先级
Java提供了一个线程调度器来监控程序启动后进去就绪状态的所有线程。线程调度器通过线程的优先级来决定调度哪些线程执行。一般来说,Java的线程调度器采用时间片轮转算法使多个线程轮转获得CPU的时间片。
线程可以划分优先级,优先级高的线程得到的CPU资源比较多,也就是CPU优先执行优先级高的线程对象中的任务。优先级具有随机性,不一定优先级高的有限制性。
2、优先级说明
- 当线程的优先级没有指定时,所有线程都携带普通优先级。
- 优先级可以用从1到10的范围指定。10表示最高优先级,1表示最低优先级,5是普通优先级。
- 优先级最高的线程在执行时被给予优先。但是不能保证线程在启动时就进入运行状态。
- 与在线程池中等待运行机会的线程相比,当前正在运行的线程可能总是拥有更高的优先级。
- 由调度程序决定哪一个线程被执行。
- t.setPriority()用来设定线程的优先级。
- 在线程开始方法被调用之前,线程的优先级应该被设定。
- 可以使用常量,如MIN_PRIORITY,MAX_PRIORITY,NORM_PRIORITY来设定优先级。
3、Thread类优先级源码
// 优先级
private int priority;
// 获取优先级
public final int getPriority() {
return priority;
}
// 设置优先级,java中规定线程优先级是1~10 的整数,较大的优先级能提高该线程被 CPU 调度的机率
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
/**
* 线程可以具有的最低优先级
*/
public final static int MIN_PRIORITY = 1;
/**
* 分配给线程的默认优先级。
*/
public final static int NORM_PRIORITY = 5;
/**
* 线程可以具有的最大优先级。
*/
public final static int MAX_PRIORITY = 10;
从源码中我们可以看到,设置优先级不能小于1,且不能大于10。
4、设置优先级案例
public class Test001 {
public static void main(String[] args) {
MyThread001 thread001 = new MyThread001();
// 设置优先级最高
thread001.setPriority(Thread.MAX_PRIORITY);
thread001.start();
// 设置优先级最低
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
// 打印优先级
System.out.println("thread001优先级:"+thread001.getPriority());
System.out.println("Main 优先级:"+Thread.currentThread().getPriority());
System.out.println(Thread.currentThread().getName() + "线程正在运行任务");
}
}
5、补充说明
如果设置线程的优先级大于线程组的优先级,指定的优先级将会失效,我们可以测试下:
public static void main(String[] args) {
ThreadGroup threadGroup = new ThreadGroup("test");
threadGroup.setMaxPriority(7);
Thread ta = new Thread(threadGroup, "thread");
ta.setPriority(10);
System.out.println(ta.getPriority());//7
}
在上面的main函数中我们定义了一个线程组指定优先级为7,然后又在该线程组中加入了一个线程,同时将该线程优先级设置为10,但是我们在获取后该线程的优先级却是7,所以说当线程的优先级超过线程组设置的优先级时会失效,但是如果我们不设置优先级呢,默认的优先级是多少呢?
public static void main(String[] args) {
System.out.println("主线程优先级:"+Thread.currentThread().getPriority());//主线程优先级:5
Thread ta=new Thread("thread");
System.out.println("线程优先级:"+ta.getPriority());//线程优先级:5
}
可以看到根据上面程序输出默认优先级为5,由于main线程的优先级为5,而main线程又是所有线程的父线程,所以线程不设置优先级的话默认都为5。
6、总结
以上就是Thread线程类设置优先级的全部内容。