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