java多線程優先級問題
阿新 • • 發佈:2017-06-28
優先 public 例子 問題 多線程 rgs 們的 線程 system
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多線程優先級問題