java线程优先级

Java线程可以有优先级的设定,高优先级的线程比低优先级的线程有更高的几率得到执行,注意是更高的几率而不是优先执行,记住当线程的优先级没有指定时,所有线程都携带普通优先级。

  1. 优先级可以用从1到10的范围指定。10表示最高优先级,1表示最低优先级,5是普通优先级。
  2. 记住优先级最高的线程在执行时被给予优先,但是不能保证线程在启动时就进入运行状态。
  3. 与在线程池中等待运行机会的线程相比,当前正在运行的线程可能总是拥有更高的优先级。
  4. 由调度程序决定哪一个线程被执行。
  5. t.setPriority()用来设定线程的优先级。
  6. 记住在线程开始方法被调用之前,线程的优先级应该被设定。
 
   

对优先级操作的方法:

 
   

int getPriority():得到线程的优先级

 
   

void setPriority(int newPriority):当线程被创建后,可通过此方法改变线程的优先级

 
   

必须指出的是:线程的优先级无法保障线程的执行次序。只不过,优先级高的线程获取CPU资源的概率较大。


下面是应用实例:

class MyThread extends Thread{ String m; MyThread(String m){ this.message=m; } public void run(){ for(int i=0;i<3;i++){ System.out.println(m+" "+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(); } }

转载于:https://www.cnblogs.com/zhc8016/p/10655821.html

你可能感兴趣的:(java)