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
    
  • 相关阅读:
    SQL未能排它地锁定数据库以执行该操作解决
    SQL日志文件丢失,只有MDF恢复
    ASP.Net2.0使用Log4Net(一)
    ASP.NET使用Memcached高缓存实例(初级教程)
    ASP.Net2.0使用Log4Net(二)
    Windows Server 2003域控制器的建立
    什么是SIP?
    [转].NET破解体验 ildasm.exe的使用
    Memcached深度分析(转载)
    X509证书帮助类
  • 原文地址:https://www.cnblogs.com/happysml/p/13835139.html
Copyright © 2011-2022 走看看