Java中的線程的優先順序

來源:互聯網
上載者:User

標籤:數字   設定   時間片   for   tar   範圍   預設   方法   優先順序   

Java 中線程優先順序簡介:

  1. Java 提供一個線程調度器來監控程式中啟動後進入就緒狀態的所有線程。

    按照線程的優先順序決定應該調度哪個線程來執行.

  2. 線程的優先順序用數字表示, 範圍從 1 到 10, 一個線程的預設優先順序是 5.

    Thread.MIN_PRIORITY = 1;

    Thread.MAX_PRIORITY = 10;

    Thread.NORM_PRIORITY = 5;

  3. 使用下述方法獲得、或設定線程對象的優先順序.

    int getPriority();

    void setPriority(int newPriority);

【注】線程的優先順序越高的, 得到的 CPU 執行的時間片就越多.(每個線程都有自己的優先順序)

Demo_1:

public class TestPriority {public static void main(String[] args){T1 t1 = new T1();T2 t2 = new T2();Thread tt1 = new Thread(t1);Thread tt2 = new Thread(t2);tt1.setPriority(Thread.NORM_PRIORITY + 3); // tt1 的優先順序提高了, 得到 CPU 執行的時間片多了tt1.start();tt2.start();}}class T1 implements Runnable {@Overridepublic void run() {for(int i = 0; i < 100; i++){System.out.println("T1: "+i);}}}class T2 implements Runnable {@Overridepublic void run() {for(int i = 0; i < 200; i++){System.out.println("---T2: "+i);}}}

 Demo_2:

 

Java中的線程的優先順序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.