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

    多线程优先级:

    多线程优先级为1~10,数字越大,优先级越高。

    一个线程不设置优先级的话,默认优先级为5;

    /**
         * 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;
    

    以上,是Thread类提供的三个优先级常量。

    设置优先级的方法为,Thread对象或继承了Thread类的对象,调用setPriority( )方法。

    实例:

    package com.xm.thread.t_19_01_26;
    
    import java.util.concurrent.TimeUnit;
    
    public class PriorityThread {
    
        public static void main(String[] args) throws InterruptedException {
            HightPriorityThread hightPriorityThread = new HightPriorityThread();
            LowPriorityThread lowPriorityThread = new LowPriorityThread();
    
            hightPriorityThread.setPriority(Thread.MAX_PRIORITY);
            lowPriorityThread.setPriority(Thread.MIN_PRIORITY);
    
            lowPriorityThread.start();
            hightPriorityThread.start();
    
            TimeUnit.SECONDS.sleep(1);
    
            System.out.println("默认优先级别!");
        }
    
    }
    
    class HightPriorityThread extends Thread{
    
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("优先级别高!");
        }
    }
    
    class LowPriorityThread extends Thread{
    
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("优先级别低!");
        }
    }
    
    

    运行结果:

    第1次运行结果:

    优先级别高!

    默认优先级别!

    优先级别低!

    第2次运行结果:

    默认优先级别!

    优先级别高!

    优先级别低!

    结果分析:

    虽然优先级别可以设置,但通过以上运行结果我们可以看出,它并不能真正控制线程在CPU上的调度顺序。

  • 相关阅读:
    PHP常用字符串函数
    PHP 中解析 url 并得到 url 参数
    PHP中的10个实用函数
    虚拟主机知识全解
    php三种常用的加密解密算法
    Javascript中的位运算符和技巧
    ECMAScript 5中新增的数组方法
    捕捉小括号获取的内容保存在RegExp的$1 $2..属性中
    js获取浏览器窗口的大小
    关于switch的思考和总结
  • 原文地址:https://www.cnblogs.com/TimerHotel/p/thread03.html
Copyright © 2011-2022 走看看