从源码看Thread的“生老病死”

最近接手的项目中涉及了一些多线程编程的内容,因此又重新对多线程相关的部分内容进行了学习,本文主要记录了一些对Thread类源码的学习笔记,不一定对,仅供个人复习以及有需要的小伙伴参考。由于C语言水平有限,未涉及本地方法的内容,对于本地方法,目前只知道它是干啥的,不知道具体实现,完全黑盒。。。

一、前述

1、registerNatives()方法

不只是在Thread类的源码中出现了registerNatives()方法,在许多JDK提供的类中都有该方法的身影,一般都是以以下4行代码的形式出现的:

private static native void registerNatives();
    static {
   
        registerNatives();
    }

registerNatives()方法是一个本地方法,这四行代码保证了该方法在类初始化完成后必然被运行一次,该方法的作用在System类的注解中进行了简要说明:

public final class System {
   
 /* register the natives via the static initializer.
     *
     * VM will invoke the initializeSystemClass method to complete
     * the initialization for this class separated from clinit.
     * Note that to use properties set by the VM, see the constraints
     * described in the initializeSystemClass method.
     */
    private static native void registerNatives();
//省略其他内容。。。
}

简单来说,该方法的作用就是注册本类中的本地方法(用关键字native进行声明)。Java语言是平台无关的语言,但是本地方法是平台有关的,换言之,通过平台有关的本地方法实现了Java平台无关的特性(纯个人理解)。对本方法感兴趣的,可以参阅Object类中的registerNatives方法的作用深入介绍.

2、SecurityManager

源码中涉及不少有关SecurityManager的内容,这块个人确实不怎么懂,推荐【基础】安全管理器SecurityManager,讲的比较容易理解。

3、Thread的状态

在Thread类的内部通过一个枚举类定义了Thread的6种状态:

//since 1.5
public enum State {
   
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

注释中对这六种状态以及各种状态出现的情形进行了简要描述,一个Thread对象“生老病死”的一生,就在这六种状态之间流转,始于NEW而终于TERMINATED,后续的内容也主要围绕这六种状态的流转进行。

二、Thread的产生

Thread类中提供了包括无参构造在内的9种构造方法(具体的构造方法可自行参阅源码或API),而这些构造方法最终都是调用init()方法来完成Thread对象的初始化,因此Thread产生的核心过程在方法init()中。

/**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if null
     * @param inheritThreadLocals if {@code true}, inherit initial values for
     *            inheritable thread-locals from the constructing thread
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
   
        if (name == null) {
   
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
   
            /* Determine if it&
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值