初始多线程(三)

一、yield方法()

    作用:放弃当前的CPU资源,将它让给其它的任务去占用CPU执行时间,但是放弃的时间不确定,有可能刚刚放弃,马上又获得CPU时间片

    测试:

public class MyThread1 extends Thread {
    @Override
    public void run() {
        System.out.println("MyThread1 run priority = "+this.getPriority());
        MyThread2 thread2 = new MyThread2();
        thread2.start();
    }
}
public class MyThread2 extends Thread{
    @Override
    public void run() {
        System.out.println("MyThread2 run priority = "+this.getPriority());
    }
}
public class Run1 {
    public static void main(String[] args) {
        System.out.println("main thread begin priority = "+Thread.currentThread().getPriority());
        System.out.println("main thread end priority = "+Thread.currentThread().getPriority());
        //Thread.currentThread().setPriority(10);
        MyThread1 thread1 = new MyThread1();
        thread1.start();
    }
}

二、线程的优先级

    在操作系统中,线程可以划分优先级,优先级较高的线程得到CPU资源较多,也就是CPU优先执行优先级比较高的线程对象中的任务。
设置线程优先级有助于帮"线程规划器"确定下一次选择哪一个线程来优先执行。

设置线程优先级使用setPriority()方法,源代码如下:

public final void setPriority(int newPriority) {
        ThreadGroup g;
        checkAccess();
        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
            throw new IllegalArgumentException();
        }
        if((g = getThreadGroup()) != null) {
            if (newPriority > g.getMaxPriority()) {
                newPriority = g.getMaxPriority();
            }
            setPriority0(priority = newPriority);
        }
    }

    在Java中,线程的优先级氛围1-10这10个等级,如果小于1或者大于10,则JDK抛出异常throw new IllegalArgumentException()。

JDK中使用3个常量来预置定义优先级的值.代码如下:

/**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

    在Java中,线程的优先级具有继承特性,比如A线程启动B线程,则B线程的优先级与A线程是一样的。

    高优先级的线程总是大部分先执行完,但不代表高优先级的线程全部先执行完。
    当线程优先级的等级差距很大时,谁先执行完和代码的调用顺序无关。(线程的优先级与代码的执行顺序无关)

    线程的优先级具有一定的规则性,也就是CPU尽量将执行资源让给优先级比较高的线程。

    线程的优先级具有"随机性",也就是优先级较高的线程不一定每一次都先执行完。

    不要把线程的优先级与运行结果的顺序作为衡量的标准,优先级较高的线程并不一定每一次都先执行完run()方法中的任务,也就是说,线程的优先级与打印顺序无关,不要将这两者的关系相关联,它们的关系具有不确定性和随机性。

    在Java中有两种线程,一种是用户线程,一种是守护(Daemon)线程。
    守护线程是一种特殊的线程,它的特性有陪伴的含义,当进程中不存在非守护线程了,则守护线程自动销毁。典型的守护线程就是垃圾回收线程,当进程中没有非守护线程了,则垃圾回收线程也就没有存在的必要了,自动销毁。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值