多线程 - 6.线程的优先级与保护线程

  1. CPU 优先执行优先级较高的线程对象中的任务。
  2. 设置线程的优先级使用 setPriority() 方法。
  3. JDK 中常使用三个预定义的常量来控制线程的优先级
    • public final static int MIN_PRIORITY = 1;
      public final static int NORM_PRIORITY = 5;
      public final static int MAX_PRIORITY = 10;

  1. 线程的优先级一共划分为 1 ~ 10 的十个等级,如果小于 1 或者大于 10 的情况下,JDK 会抛出异常 throw new IllegalArgumentException()。
  2. 线程的优先级有继承性、规则性、随机性。
  1. 守护线程即是一种特殊的线程 ( Daemon ) ,当进程中不存在用户线程后,则守护线程即会自动销毁。java 的垃圾回收线程也是守护线程之一。
  2. 用户也可以自行设置自身的某一线程为守护线程 , Thread.setDeamon(true);
class ThreadA extends Thread{
    private int i =0;
    @Override
    public void run(){
        try{
            while(true){
                i++;
                System.out.println("i=" + i);
                Thread.sleep(1000);
            }
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
}

public class test1{
    public static void main(String[] args){
        Thread a = new ThreadA();
        a.setDaemon(true);
        a.start();
        try{
            a.sleep(5000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.print("停止之后,守护线程再也无法进行打印");
    }
}

i=1
i=2
i=3
i=4
i=5
停止之后,守护线程再也无法进行打印

  1. yield() 函数的作用是放弃当前的 CPU 资源,但是放弃的时间并不确定。
class ThreadA extends Thread{
    @Override
    public void run(){
        long begin = System.currentTimeMillis();
        int count = 0;
        for(int i = 0; i < 1000000; i++){
            Thread.yield();
            count = count+i;
        }
        long end = System.currentTimeMillis();
        System.out.print("总耗时" + (end - begin));
    }
}

public class test0{
    public static void main(String[] args){
        Thread a = new ThreadA();
        a.start();
    }
}

注释掉:Thread.yield();
总耗时3
不注释
总耗时670

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值