從線程的優先級看饑餓問題
阿新 • • 發佈:2017-12-08
string sta roo prior 不同 start 有意 target style
饑餓與公平:
1.高優先級吞噬所有低優先級的CPU時間片
2.線程被永久堵塞在一個等待進入同步塊的狀態
3.等待的線程永遠不被喚醒
關於優先級,編程的時候註意:
不要假定高優先級的線程一定先於低優先級的線程,不要有邏輯依賴線程優先級,否則可能有意外錯誤。因為,不同的平臺,對於同一個優先級的數值,可能代表的含義不一樣。
但是,大多數我們看到的還是,優先級高的,搶到CPU的概念執行更高。
package com.roocon.thread.t4; public class Target implements Runnable{ @Override public void run() {while(true){ System.out.println(Thread.currentThread().getName()+"is running"); } } }
package com.roocon.thread.t4; public class Demo { public static void main(String[] args) { Thread t0 = new Thread(new Target()); Thread t1 = new Thread(new Target()); t0.setPriority(Thread.MAX_PRIORITY); t1.setPriority(Thread.MIN_PRIORITY); t0.start(); t1.start(); } }
運行結果:
Thread-1is running Thread-1is running Thread-1is running Thread-1is running Thread-1is running Thread-1is running Thread-1is running Thread-1is running Thread-1is running Thread-1is running
...//大多數都是Thread-1is running,偶爾是Thread-0is running
Thread-1is running
從線程的優先級看饑餓問題