zoukankan      html  css  js  c++  java
  • 线程的优先级(读书笔记)

         Java中的线程可以有自己的优先级,优先级高的线程在竞争资源时会更有优势,更可能抢占资源.
         Java中 使用1到10表示线程优先级,一般可以使用内置的三个静态变量表示:
     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;
     
         数字越大则优先级越高,但有效范围在1到10之间, 高优先级的线程倾向于更快的完成工作.
    public class PriorityDemo {
        public static class HightProprity extends Thread {
            static int count = 0;
    
            public void run() {
                while (true) {
                    synchronized (PriorityDemo.class) {
                        count++;
                        if (count > 10000000) {
                            System.out.println("HightPriority is complete");
                            break;
                        }
                    }
                }
            }
        }
    
        public static class LowPriority extends Thread {
            static int count = 0;
    
            public void run() {
                while (true) {
                    synchronized (PriorityDemo.class) {
                        count++;
                        if (count > 10000000) {
                            System.out.println("LowPriority is complete");
                            break;
                        }
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            Thread high = new HightProprity();
            Thread low = new LowPriority();
            high.setPriority(Thread.MAX_PRIORITY);
            low.setPriority(Thread.MIN_PRIORITY);
            low.start();
            high.start();
        }
    }
    我们尝试执行上述代码,可以看到 大部分情况下.高优先级的线程大部分情况下,就会首先完成任务.
     
     
  • 相关阅读:
    移植thinkPHP的dump()函数
    PHP生成linux命令行进度条
    没有ORM库的时候,通过PDO连接MySQL的方法
    mysql json字符串 解析成对应字段
    linux上安装并启动nginx
    linux上启动redis
    mui的input搜索框里的清除按钮的点击监听事件
    miniui 修改input样式及弹出框按钮文字
    js 删除数组元素的方法
    miniui反选
  • 原文地址:https://www.cnblogs.com/ten951/p/6171044.html
Copyright © 2011-2022 走看看