zoukankan      html  css  js  c++  java
  • 线程优先级

    线程优先级

    • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
    • 线程的优先级用数字表示,范围从1-10
    • 可以使用个体Priority()查看线程的优先级,setPriority(int)设置线程的优先级

    源码

     /**
      * The minimum priority that a thread can have.
      */
     public final static int MIN_PRIORITY = 1;
    
    /**
      * The default priority that is assigned to a thread.
      */
     public final static int NORM_PRIORITY = 5;
    
     /**
      * The maximum priority that a thread can have.
      */
     public final static int MAX_PRIORITY = 10;
    
    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);
        }
    }
    
    /**
     * Returns this thread's priority.
     *
     * @return  this thread's priority.
     * @see     #setPriority
     */
    public final int getPriority() {
        return priority;
    }
    

    例子

    package MultiProcess;
    
    //测试线程的优先级
    public class TestPriority extends Thread{
        public static void main(String[] args) {
            //主线程默认优先级
            System.out.println(Thread.currentThread().getName() + "-->" +
                    Thread.currentThread().getPriority());
    
            MyPriority myPriority = new MyPriority();
    
            Thread thread1 = new Thread(myPriority);
            Thread thread2 = new Thread(myPriority);
    
            thread1.setPriority(2);
            thread2.setPriority(8);
    
            thread1.start();
            thread2.start();
    
        }
    }
    
    class MyPriority implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "-->" +
                    Thread.currentThread().getPriority());
        }
    }
    
    结果
    main-->5
    Thread-1-->8
    Thread-0-->2
    
  • 相关阅读:
    zookeeper和Eureka对CAP理论的支持
    redis缓存穿透、缓存击穿、缓存雪崩
    CAP原则和BASE理论
    bin log、redo log、undo log和MVVC
    在ROS中使用Python3
    Windows下使用AutoSSH,并作为服务自启动(不用安装Cygwin)
    回收站的正确使用方法
    Windows下好用到必须开机自启的小工具
    PreferenceScreen监听子项的刷新
    安卓普通类通过classloader访问资源文件
  • 原文地址:https://www.cnblogs.com/happysml/p/13835139.html
Copyright © 2011-2022 走看看