线程的优先级用数字来表示,默认范围是1到10,即Thread.MIN_PRIORITY到Thread.MAX_PRIORTY.一个线程的默认优先级是5,即Thread.NORM_PRIORTY
对优先级操作的方法:
int getPriority():得到线程的优先级
void setPriority(int newPriority):当线程被创建后,可通过此方法改变线程的优先级
必须指出的是:线程的优先级无法保障线程的执行次序。只不过,优先级高的线程获取CPU资源的概率较大。
class MyThread extends Thread{ String message; MyThread(String message){ this.message=message; } public void run(){ for(int i=0;i<3;i++){ System.out.println(message+" "+getPriority()); } } } public class PriorityThread{ public static void main(String args[]){ Thread t1=new MyThread("T1"); t1.setPriority(Thread.MIN_PRIORITY); t1.start(); Thread t2=new MyThread("T2"); t2.setPriority(Thread.MAX_PRIORITY); t2.start(); Thread t3=new MyThread("T3"); t3.setPriority(Thread.MAX_PRIORITY); t3.start(); } }