在多執行緒應用程式中,每個執行緒都被指派一個優先權。處理器根據執行緒的優先權(即最高優先權的執行緒先分配處理器,依此類推)由執行緒調度器分配給執行緒。執行緒的預設優先權為5。我們可以使用Thread類別的getPriority()方法來取得執行緒的優先權。
在Thread類別中,定義了三個靜態值來表示執行緒的優先權:
這是最高的執行緒優先權,值為 10。
這是預設的執行緒優先權,值為5。
這是最低的執行緒優先權,值為1。
public final int getPriority()
public class ThreadPriorityTest extends Thread { public static void main(String[]args) { ThreadPriorityTest thread1 = new ThreadPriorityTest(); ThreadPriorityTest thread2 = new ThreadPriorityTest(); ThreadPriorityTest thread3 = new ThreadPriorityTest(); System.out.println("Default thread priority of thread1: " + thread1.<strong>getPriority</strong>()); System.out.println("Default thread priority of thread2: " + thread2.<strong>getPriority</strong>()); System.out.println("Default thread priority of thread3: " + thread3.<strong>getPriority</strong>()); thread1.setPriority(8); thread2.setPriority(3); thread3.setPriority(6); System.out.println("New thread priority of thread1: " + thread1.<strong>getPriority()</strong>); System.out.println("New thread priority of thread2: " + thread2.<strong>getPriority()</strong>); System.out.println("New thread priority of thread3: " + thread3.<strong>getPriority()</strong>); } }
Default thread priority of thread1: 5 Default thread priority of thread2: 5 Default thread priority of thread3: 5 New thread priority of thread1: 8 New thread priority of thread2: 3 New thread priority of thread3: 6
以上是在Java中,執行緒優先權的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!