1. 線程優先順序的介紹
java 中的線程優先順序的範圍是1~10,預設的優先順序是5。“高優先順序線程”會優先於 “低優先順序線程”執行。
java 中有兩種線程:使用者線程和守護線程。可以通過isDaemon()方法來區別它們:如果返回false, 則說明該線程是“使用者線程”;否則就是“守護線程”。
使用者線程一般使用者執 行使用者級任務,而守護線程也就是“後台線程”,一般用來執行背景工作。需要注意的是: Java虛擬機器在“使用者線程”都結束後會後退出。
JDK 中關於線程優先順序和守護線程的介紹如下:
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon. When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs: The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method. Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
大致意思是:
每個線程都有一個優先順序。“高優先順序線程”會優先於“低優先順序線程”執行 。每個線程都可以被標記為一個守護進程或非守護進程。在一些啟動並執行主線程中建立新的子線程時,子線 程的優先順序被設定為等於“建立它的主線程的優先順序”,若且唯若“建立它的主線程是 守護線程”時“子線程才會是守護線程”。
當Java虛擬機器啟動時,通常有一個單一的非守護線程(該線程通過是通過main()方法啟動)。JVM會一 直運行直到下面的任意一個條件發生,JVM就會終止運行:
(01) 調用了exit()方法,並且exit()有權 限被正常執行。
(02) 所有的“非守護線程”都死了(即JVM中僅僅只有“守護線程 ”)。
每一個線程都被標記為“守護線程”或“使用者線程”。當只有守護線程運行時 ,JVM會自動結束。
2. 線程優先順序的樣本
我們先看看優先順序的樣本
class MyThread extends Thread{ public MyThread(String name) { super(name); } public void run(){ for (int i=0; i<5; i++) { System.out.println(Thread.currentThread().getName() +"("+Thread.currentThread().getPriority()+ ")" +", loop "+i); } } }; public class Demo { public static void main(String[] args) { System.out.println(Thread.currentThread().getName() +"("+Thread.currentThread().getPriority()+ ")"); Thread t1=new MyThread("t1"); // 建立t1 Thread t2=new MyThread("t2"); // 建立t2 t1.setPriority(1); // 設定t1的優先順序為1 t2.setPriority(10); // 設定t2的優先順序為10 t1.start(); // 啟動t1 t2.start(); // 啟動t2 } }
運行結果
main(5)t1(1), loop 0t2(10), loop 0t1(1), loop 1t2(10), loop 1t1(1), loop 2t2(10), loop 2t1(1), loop 3t2(10), loop 3t1(1), loop 4t2(10), loop 4
結果說明:
(01) 主線程main的優先順序是5。
(02) t1的優先順序被設為1,而t2的優先順序被設為10 。cpu在執行t1和t2的時候,根據時間片輪循調度,所以能夠並發執行。