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

      在初识并发这篇博客提到过,Java的线程机制是抢占式的:这表示调度机制会周期性地中断线程,将上下文切换到另一个线程,从而为每隔线程都提供时间片,使得每个线程都会分配到数量合理的时间去驱动它的任务。

      尽管CPU处理现有线程集的顺序是不确定的,但是调度器倾向于让优先权最高的线程先执行,而优先权较低的线程并非没有机会执行,只是执行的频率较低。我们可以用getPriority()读取现有线程的优先级,使用setPriority来修改它:

    public class LiftOff implements Runnable {
        
        public LiftOff(int priority){
            taskCount++;// 计数自增
            this.priority = priority;
        }
    
        private int        countDown = 3;        // 倒计时数字
    
        private static int taskCount = 0;
    
        private int        id        = taskCount;
        
        private int priority;
        
        @Override
        public void run() {
            Thread.currentThread().setPriority(priority);//设置优先级 Thread.currentThread()可获得对驱动该任务的Thread()对象的引用
            while (countDown >= 0) {
                System.out.println("线程编号" + id + "--倒计时" + countDown);
                countDown--;
                if(countDown < 0){
                    System.out.println(Thread.currentThread() + ":" + id);
                }
            }
        }
    }

    调用线程启动任务:

    public class Launch {
    
        public static void main(String[] args) {
            ExecutorService executor = Executors.newCachedThreadPool();
            executor.execute(new LiftOff(Thread.MAX_PRIORITY));
            executor.execute(new LiftOff(Thread.MIN_PRIORITY));
        }
    }

    输出:

    线程编号0--倒计时3
    线程编号1--倒计时3
    线程编号1--倒计时2
    线程编号0--倒计时2
    线程编号0--倒计时1
    线程编号0--倒计时0
    线程编号1--倒计时1
    Thread[pool-1-thread-1,10,main]:0
    线程编号1--倒计时0
    Thread[pool-1-thread-2,1,main]:1

      可以发现我们通过构造函数设置的线程优先级并没有起到预想的效果,setPriority只是给线程调度提提供建议,但这些建议未必会有效果

      所以,在绝大多数时间里,所有线程都应该以默认的优先级运行。试图操纵线程优先级通常是一种错误。

  • 相关阅读:
    【论文阅读】A practical algorithm for distributed clustering and outlier detection
    第11组 团队Git现场编程实战
    第11组 团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
    第11组 团队展示
    第一次结对编程作业
    第一次个人编程作业
    第一次博客作业
    (转)script标签到底该放在哪里
  • 原文地址:https://www.cnblogs.com/qilong853/p/5897033.html
Copyright © 2011-2022 走看看