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
    
  • 相关阅读:
    PAT L3-021 神坛
    2019.07.08【NOIP提高组】模拟 A 组 总结
    2019.07.06【NOIP提高组】模拟 A 组 总结
    2019.07.05【NOIP提高组】模拟 A 组 总结
    jzoj 1287. 躲雨
    jzoj 4614. 【NOIP2016模拟7.12】字符串
    jzoj 3317. 【BOI2013】管道
    2019.07.04【NOIP提高组】模拟 A 组
    jzoj 3316. 【BOI2013】非回文数字
    jzoj 4616. 【NOI2016模拟7.12】二进制的世界
  • 原文地址:https://www.cnblogs.com/happysml/p/13835139.html
Copyright © 2011-2022 走看看