CPU 在某一個時刻只能執行一條指令,線程只有獲得CPU時間片,也就是CPU的使用權,才能夠執行指令。在單CPU 的機器上線程不是並行運行的,只是各線程在不斷的切換執行,感受上像是並行執行。只有在多個CPU 上的線程才能夠並行運行,每一個CPU執行一個線程(是理想狀態),即便是多個CPU的計算機,每一個CPU也在同時執行着多個進程或線程。Java 虛擬機負責線程的調度,取得CPU 的使用權分配給不一樣的線程。CPU調度模型分爲:分時調度模型和搶佔式調度模型,Java 使用搶佔式調度模型。分時調度模型:全部線程輪流獲得CPU 的使用權,平均分配每一個線程佔用CPU 的時間片。搶佔式調度模型:優先讓優先級高的線程使用CPU,若是線程的優先級相同,那麼會隨機選擇一個,優先級高的線程獲取的CPU 時間片相對要多一些。this
在Java中,線程是能夠設置執行優先級的。Thread類中有三個靜態變量,用來表示線程的優先級。線程的的優先級從1~10,1的優先級最低,10的優先選最高,默認狀況下的優先級是5。Java中線程的優先級默認是5。spa
MAX_PRIORITY:優先級最高,值爲10線程
MIN_PRIORITY:優先級最低,值爲1對象
NORM_PRIORITY:默認優先級,值爲5進程
public class SvnVersion {
public static void main(String[] args){
Thread thread = new Process01();
thread.start();
System.out.println("最大優先級:"+Thread.MAX_PRIORITY);
System.out.println("最大優先級:"+Thread.NORM_PRIORITY);
System.out.println("最大優先級:"+Thread.MIN_PRIORITY);
}
}get
class Process01 extends Thread{
public void run (){
System.out.println("輸出當前線程優先級:"+this.getPriority());
}
}虛擬機
public class SvnVersion {
public static void main(String[] args) throws InterruptedException{
ExecutorService eService=Executors.newFixedThreadPool(5);
for(int i=1;i<=10;i++){
Thread thread=new Process01();
thread.setPriority(i);
eService.submit(thread);
}
Thread.currentThread().setPriority(10);
for (int i = 0; i < 10; i++) {
System.out.println("main:"+i);
}
}
}it
class Process01 extends Thread{
public void run (){
System.out.println("輸出當前子線程優先級:"+this.currentThread().getName()+"--"+this.getPriority());
for (int i = 0; i < 10; i++) {
System.out.println("子線程:"+this.currentThread().getName()+"--"+i);
}
}
}io