- CPU 優先執行優先級較高的線程對象中的任務。
- 設置線程的優先級使用 setPriority() 方法。
- JDK 中常使用三個預定義的常量來控制線程的優先級
-
-
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
-
- 線程的優先級一共劃分爲 1 ~ 10 的十個等級,如果小於 1 或者大於 10 的情況下,JDK 會拋出異常 throw new IllegalArgumentException()。
- 線程的優先級有繼承性、規則性、隨機性。
- 守護線程即是一種特殊的線程 ( Daemon ) ,當進程中不存在用戶線程後,則守護線程即會自動銷燬。java 的垃圾回收線程也是守護線程之一。
- 用戶也可以自行設置自身的某一線程爲守護線程 , Thread.setDeamon(true);
class ThreadA extends Thread{
private int i =0;
@Override
public void run(){
try{
while(true){
i++;
System.out.println("i=" + i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public class test1{
public static void main(String[] args){
Thread a = new ThreadA();
a.setDaemon(true);
a.start();
try{
a.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print("停止之後,守護線程再也無法進行打印");
}
}
i=1
i=2
i=3
i=4
i=5
停止之後,守護線程再也無法進行打印
- yield() 函數的作用是放棄當前的 CPU 資源,但是放棄的時間並不確定。
class ThreadA extends Thread{
@Override
public void run(){
long begin = System.currentTimeMillis();
int count = 0;
for(int i = 0; i < 1000000; i++){
Thread.yield();
count = count+i;
}
long end = System.currentTimeMillis();
System.out.print("總耗時" + (end - begin));
}
}
public class test0{
public static void main(String[] args){
Thread a = new ThreadA();
a.start();
}
}
註釋掉:Thread.yield();
總耗時3
不註釋
總耗時670