線程Priority:
線程可以划分優先級,優先級較高的線程得到的CPU資源較多,也就是CPU優先執行優先級較高的線程對象中的任務。
設置線程優先級有助於幫助“線程規划器”確定在下一次選擇哪個線程來優先執行。
線程優先級分為10個等級,1-》10
三個常用等級:
線程優先級繼承性:
A線程啟動了B線程,則B線程的優先級與A線程是一樣的。
public class PriorityInheritThread extends Thread { @Override public void run() { System.out.println("1 Run priority = " + this.getPriority()); PriorityInheritThread2 thread2 = new PriorityInheritThread2(); thread2.start(); } } public class PriorityInheritThread2 extends Thread{ @Override public void run() { System.out.println("2 Run priority = " + this.getPriority()); } } public class ThreadRunMain { public static void main(String[] args) { testPriorityInheritThread(); } public static void testPriorityInheritThread() { System.out.println("Main thread begin priority = " + Thread.currentThread().getPriority()); Thread.currentThread().setPriority(6); System.out.println("Main thread end priority = " + Thread.currentThread().getPriority()); PriorityInheritThread thread1 = new PriorityInheritThread(); thread1.start(); } }
運行結果:
線程規則性:
優先級高的線程總是大部分先執行完。
線程隨機性:
當線程優先等級差距很大,誰先執行完和Main線程代碼的調用順序無關。優先級高的線程也不一定每一次都先執行完。
public class RunFastThreadA extends Thread { private int count = 0; public int getCount() { return count; } @Override public void run() { while(true){ count ++; } } } public class RunFastThreadB extends Thread { private int count = 0; public int getCount() { return count; } @Override public void run() { while(true){ count ++; } } } public class ThreadRunMain { public static void main(String[] args) { testRunFastThread(); } public static void testRunFastThread() { try { RunFastThreadA a = new RunFastThreadA(); a.setPriority(Thread.NORM_PRIORITY - 3); a.start(); RunFastThreadB b = new RunFastThreadB(); b.setPriority(Thread.NORM_PRIORITY + 3); b.start(); Thread.sleep(10000); a.stop(); b.stop(); System.out.println("a = " + a.getCount()); System.out.println("b = " + b.getCount()); } catch (InterruptedException e) { e.printStackTrace(); } } }
運行結果: