zoukankan      html  css  js  c++  java
  • 线程优先级介绍以及设置

    相关属性

    在 Thread 源码中和线程优先级相关的属性有 3 个:

    // 线程可以拥有的最小优先级
    public final static int MIN_PRIORITY = 1;
    
    // 线程默认优先级
    public final static int NORM_PRIORITY = 5;
    
    // 线程可以拥有的最大优先级
    public final static int MAX_PRIORITY = 10
    

    线程的优先级可以理解为线程抢占 CPU 时间片的概率,优先级越高的线程优先执行的概率就越大,但并不能保证优先级高的线程一定先执行。

    优先级设置

    在程序中我们可以通过 Thread.setPriority() 来设置优先级,setPriority() 源码如下:

    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);
        }
    }
    
  • 相关阅读:
    第2课:关闭被黑客扫描的端口
    CentOS安装zip及用法
    网络安全目录
    第1课:电脑基础命令讲解
    SQL注入目录
    windows下安装redis
    CentOS安装rar及用法
    CentOS安装OpenOffice
    hadoop异常
    删除CentOS系统自带的jdk
  • 原文地址:https://www.cnblogs.com/xiaodou00/p/13499618.html
Copyright © 2011-2022 走看看