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();
        }
    }
    我们尝试执行上述代码,可以看到 大部分情况下.高优先级的线程大部分情况下,就会首先完成任务.
     
     
  • 相关阅读:
    Alien Security (BFS+DFS)
    HDU 1495 喝可乐(暴力BFS)
    Tempter of the Bone(奇偶剪枝)の反面教材
    Fire Game (双起点bfs)
    Linux学习
    c# 实现IComparable、IComparer接口、Comparer类的详解
    DataTable 基本转换简单实例
    C#集合
    递归方法
    存储过程生成复杂的随机编号
  • 原文地址:https://www.cnblogs.com/ten951/p/6171044.html
Copyright © 2011-2022 走看看