與線程休眠類似,線程的優先級仍然無法保障線程的執行次序。只不過,優先級高的線程獲取CPU資源的概率較大,優先級低的並非沒機會執行。
線程的優先級用1-10之間的整數表示,數值越大優先級越高,默認的優先級為5。
在一個線程中開啟另外一個新線程,則新開線程稱為該線程的子線程,子線程初始優先級與父線程相同。
package cn.thread; /** * 線程的調度(優先級) * * @author 林計欽 * @version 1.0 2013-7-24 上午09:30:42 */ public class ThreadPriority { public static void main(String[] args) { ThreadPriority thread=new ThreadPriority(); Thread t1 = thread.new MyThread1(); Thread t2 = new Thread(thread.new MyRunnable()); t1.setPriority(10); t2.setPriority(1); t2.start(); t1.start(); } class MyThread1 extends Thread { public void run() { for (int i = 0; i < 10; i++) { System.out.println("線程1第" + i + "次執行!"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } class MyRunnable implements Runnable { public void run() { for (int i = 0; i < 10; i++) { System.out.println("線程2第" + i + "次執行!"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } }

