线程的优先级

            一、介绍       

   在Java中,每一个线程都有一个优先级,默认是一个线程继承它的父线程的优先级。一个线程的默认优先级为NORM_PRIORITY = 5

  设置优先级的方法setPriority() ,可设置的值如下:  

1
2
3
static int MAX_PRIORITY = 10 ; //线程可以具有的最高优先级(执行概率最高)
static int MIN_PRIORITY = 1 ; //线程可以具有的最低优先级(执行概率最低)
static int NORM_PRIORITY = 5 //分配给线程的默认优先级

   线程的优先级:不是说哪个线程优先执行,如果设置某个线程的优先级高。那就是有可能被执行的概率高。并不是优先执行


 二、实例       

线程优先级实例代码:这里设置线程1为最高优先级(被执行的概率高) 设置线程2为最低优先级

这里设置了线程1最高和线程2最低优先级后,并不是说线程1就优先执行等到线程1执行完才执行线程2。而是说线程1被执行的概率高。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//线程类
public class PriorityThread implements Runnable{
     private boolean flag = true ;
     private int num= 0 ;
     @Override
     public void run() {
         while (flag){
             System.out.println(Thread.currentThread().getName()+ "-->" +num++);
         }
     }
     public void stop(){
         this .flag = ! this .flag;
     }
}
//测试线程优先级
public class PriorityDemo {
     public static void main(String[] args) throws InterruptedException {
         PriorityThread it1 = new PriorityThread();
         PriorityThread it2 = new PriorityThread();
         Thread proxy1 = new Thread(it1, "线程1" );
         Thread proxy2 = new Thread(it2, "线程2" );
         proxy1.setPriority(Thread.MAX_PRIORITY); //设置为最高优先级
         proxy2.setPriority(Thread.MIN_PRIORITY); //设置为最低优先级
         proxy1.start();
         proxy2.start();
         Thread.sleep( 1000 );
         it1.stop();
         it2.stop();
     }
}

执行结果如下:

线程1-->47755   统计共执行了4685次

线程2-->19211   统计共执行了1469次


 三、总结       

1、每个线程都有一个默认的优先级,默认情况下是NORM_PRIORITY = 5

2、线程的优先级表示的是被执行的概率,并不是绝对的优先执行。

3、设置线程优先级的方法setPriority(Thread.MAX_PRIORITY);







转载于:https://my.oschina.net/u/1045699/blog/786610

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值