首頁> Java> java教程> 主體

多執行緒中的Java執行緒優先權

王林
發布: 2023-09-06 14:21:06
轉載
738 人瀏覽過

多執行緒中的Java執行緒優先權

在多執行緒的情況下,執行緒調度程序根據不同的條件將執行緒指派給特定的行程。 他們的優先事項。 java 執行緒具有預先分配的優先權。除此之外,java虛擬 機器也可以為執行緒分配優先權或由程式設計師明確指定。範圍為 執行緒優先權的值介於 1 到 10(含)之間。三個靜態變數 與優先權相關的有 -

  • MAX_PRIORITY - 執行緒擁有的最大優先權,預設值為 10。

  • NORM_PRIORITY - 執行緒具有的預設優先級,預設值為 5。

  • MIN_PRIORITY - 執行緒具有的最小優先權,預設值為 1。

Java 中的「getPriority()」方法有助於傳回綁定為值的執行緒優先權。

「setPriority()」方法會變更給定執行緒的優先權值。它拋出 當執行緒優先權小於 1 或大於 10 時,出現 IllegalArgumentException。

範例

即時示範

import java.lang.*; public class Demo extends Thread{ public void run(){ System.out.println("Now, inside the run method"); } public static void main(String[]args){ Demo my_thr_1 = new Demo(); Demo my_thr_2 = new Demo(); System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority()); System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority()); my_thr_1.setPriority(5); my_thr_2.setPriority(3); System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority()); System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority()); System.out.print(Thread.currentThread().getName()); System.out.println("The thread priority of main thread is : " + Thread.currentThread().getPriority()); Thread.currentThread().setPriority(10); System.out.println("The thread priority of main thread is : " + Thread.currentThread().getPriority()); } }
登入後複製

輸出

The thread priority of first thread is : 5 The thread priority of first thread is : 5 The thread priority of first thread is : 5 The thread priority of first thread is : 3 The thread priority of main thread is : 5 The thread priority of main thread is : 10
登入後複製

名為 Demo 的類別繼承自基底類別 Thread。函數‘run’被定義且相關 訊息被定義。在 main 函數中,建立了 Demo 類別的兩個實例,並將它們 優先權是透過呼叫函數“getPriority”找到的。

它們被印在控制台上。接下來,使用以下方法為 Demo 實例指派優先權: ‘設定優先權’函數。輸出顯示在控制台上。列印線程的名稱 使用「getName」功能在螢幕上顯示。

以上是多執行緒中的Java執行緒優先權的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!