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
    
  • 相关阅读:
    POJ 2923 Relocation (状态压缩,01背包)
    HDU 2126 Buy the souvenirs (01背包,输出方案数)
    hdu 2639 Bone Collector II (01背包,求第k优解)
    UVA 562 Dividing coins (01背包)
    POJ 3437 Tree Grafting
    Light OJ 1095 Arrange the Numbers(容斥)
    BZOJ 1560 火星藏宝图(DP)
    POJ 3675 Telescope
    POJ 2986 A Triangle and a Circle
    BZOJ 1040 骑士
  • 原文地址:https://www.cnblogs.com/happysml/p/13835139.html
Copyright © 2011-2022 走看看