“`” 理论上来说系统会根据优先级来决定首先使哪个线程进入运行状态。当 CPU 比较闲的时候,设置线程优先级几乎不会有任何作用,而且很多操作系统压根不会不会理会你设置的线程优先级,所以不要让业务过度依赖于线程的优先级。
另外,<strong>线程优先级具有继承特性</strong>比如 A 线程启动 B 线程,则 B 线程的优先级和 A 是一样的。<strong>线程优先级还具有随机性</strong> 也就是说线程优先级高的不一定每一次都先执行完。
Thread 类中包含的成员变量代表了线程的某些优先级。如<strong>Thread.MIN_PRIORITY(常数 1)</strong>,<strong>Thread.NORM_PRIORITY(常数 5)</strong>,<strong>Thread.MAX_PRIORITY(常数 10)</strong>。其中每个线程的优先级都在<strong>1</strong> 到<strong>10</strong> 之间,在默认情况下优先级都是<strong>Thread.NORM_PRIORITY(常数 5)</strong>。
<strong>一般情况下,不会对线程设定优先级别,更不会让某些业务严重地依赖线程的优先级别,比如权重,借助优先级设定某个任务的权重,这种方式是不可取的,一般定义线程的时候使用默认的优先级就好了。</strong>
<strong>相关方法:</strong>
<pre><code>public final void setPriority(int newPriority) //为线程设定优先级public final int getPriority() //获取线程的优先级</code></pre>
<strong>设置线程优先级方法源码:</strong>
<pre><code> public final void setPriority(int newPriority) { ThreadGroup g; checkAccess(); //线程游戏优先级不能小于 1 也不能大于 10,否则会抛出异常 if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) { throw new IllegalArgumentException(); } //如果指定的线程优先级大于该线程所在线程组的最大优先级,那么该线程的优先级将设为线程组的最大优先级 if((g = getThreadGroup()) != null) { if (newPriority > g.getMaxPriority()) { newPriority = g.getMaxPriority(); } setPriority0(priority = newPriority); } }</code></pre>
<pre><code> "“`
Was this helpful?
0 /
0