標籤:logs div color 預設 set end 運行 隨機 span
java 中的線程優先順序的範圍是1~10,預設的優先順序是5。“高優先順序線程”會優先於“低優先順序線程”執行。
例子:
package com.ming.thread.threadpriority;public 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); } }}
package com.ming.thread.threadpriority;/** * 線程的優先順序的值是1--10 * @author ming * */public class Run { public static void main(String[] args) { MyThread t1=new MyThread("t1"); MyThread t2=new MyThread("t2"); MyThread t3=new MyThread("t3"); t1.setPriority(6); t2.setPriority(Thread.MAX_PRIORITY); t3.setPriority(1); t1.start(); t2.start(); t3.start(); }}
不要把線程的優先順序與運行結果的順序作為衡量的標準,優先順序較高的線程並不一定每一次都先執行完run()方法中的任務,也就是說,線程的優先順序與列印順序無關,不要將這兩者的關係相關聯,它們的關係具有不確定性和隨機性。
java多線程優先順序問題