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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值