Thread 源码阅读

Thread

  • 属性说明
/**
 *  程序中的执行线程
 * @since   1.0
 */
public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

    /**
     *  线程名称
     */
    private volatile String name;
    
    /**
     *  线程优先级 
     */
    private int            priority;
    
    /**
     *  此线程是否是守护线程  
     */
    private boolean     daemon = false;

    /**
     *  将运行的目标
     */
    private Runnable target;

    /**
     *  此线程所在的线程组
     */
    private ThreadGroup group;

    /**
     *  当前线程的上下文类加载器
     */
    private ClassLoader contextClassLoader;

    /**
     *  此线程继承的访问控制上下文
     */
    private AccessControlContext inheritedAccessControlContext;

    /**
     * 匿名线程的自增编号
     */
    private static int threadInitNumber;

    /** 与当前线程绑定的  ThreadLocalMap */
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /**
     *  继承的 ThreadLocalMap
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

    /**
     *  此线程请求的堆栈大小,如果未设置则由 JVM 自己决定
     */
    private long stackSize;

    /**
     *  此线程的 ID
     */
    private long tid;

    /**
     *  线程名称序列 ID
     */
    private static long threadSeqNumber;

    /**
     *  此线程的状态
     */
    private volatile int threadStatus;

    /**
     *  当前线程在此目标对象 parkBlocker 上阻塞
     * java.util.concurrent.locks.LockSupport.park.
     */
    volatile Object parkBlocker;

    /**
     *  阻塞此线程的可中断 IO 对象
     */
    private volatile Interruptible blocker;
    
    /**
     *  阻塞锁
     */
    private final Object blockerLock = new Object();

    /**
     *  线程的最小优先级
     */
    public static final int MIN_PRIORITY = 1;

    /**
     *  线程的默认优先级
     */
    public static final int NORM_PRIORITY = 5;

    /**
     *  线程的最大优先级
     */
    public static final int MAX_PRIORITY = 10;
  • 常用静态方法
    /**
     *  当前线程所在线程组中估计的活跃线程数
     */
    public static int activeCount() {
        return currentThread().getThreadGroup().activeCount();
    }

    /**
     *  返回当前执行线程
     */
    @HotSpotIntrinsicCandidate
    public static native Thread currentThread();

    /**
     *  打印当前线程的堆栈信息,只用于调试
     */
    public static void dumpStack() {
        new Exception("Stack trace").printStackTrace();
    }

    /**
     *  当前线程是否持有目标对象的监视器
     * @since 1.4
     */
    public static native boolean holdsLock(Object obj);

    /**
     *  返回并清空当前线程的中断状态
     *
     * @revised 6.0
     */
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

    /**
     *  让当前线程自旋等待一会
     * @since 9
     */
    @HotSpotIntrinsicCandidate
    public static void onSpinWait() {}

    /**
     *  当前线程休眠指定的毫秒数
     *
     * @param  millis   休眠的毫秒数
     */
    public static native void sleep(long millis) throws InterruptedException;

    /**
     *  当前线程愿意让步处理器时间,从运行状态进入就绪状态
     */
    public static native void yield();
  • 实例化
    /**
     *  创建运行目标任务 target 的新线程
     *
     * @param  target   目标 Runnable 任务
     */
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

    /**
     *  创建运行目标任务 target 的新线程,并指定线程名称,方便排查问题
     *
     * @param  target   目标 Runable 任务
     * @param  name     新线程的名称
     */
    public Thread(Runnable target, String name) {
        init(null, target, name, 0);
    }
  • 常用方法
    /**
     *  此线程是否还存活
     */
    public final native boolean isAlive();

    /**
     *  此线程是否是守护线程
     */
    public final boolean isDaemon() {
        return daemon;
    }

    /**
     *  此线程是否已经被设置中断标识,同时清除其中断标识。
     *
     * @revised 6.0
     */
    public boolean isInterrupted() {
        return isInterrupted(false);
    }

    /**
     *  返回线程创建时自动生成的ID
     */
    public long getId() {
        return tid;
    }

    /**
     *  读取此线程的名称
     */
    public final String getName() {
        return name;
    }

    /**
     *  读取此线程的优先级
     */
    public final int getPriority() {
        return priority;
    }

    /**
     *  返回此线程的状态
     * @since 1.5
     */
    public State getState() {
        // get current thread state
        return jdk.internal.misc.VM.toThreadState(threadStatus);
    }

    /**
     *  线程状态
     */
    public enum State {
        /**
         *  线程刚创建,还未启动
         */
        NEW,

        /**
         *  线程正在运行
         */
        RUNNABLE,

        /**
         *  此线程在等待获取指定对象的监视器,已经阻塞
         */
        BLOCKED,

        /**
         *  此线程在阻塞等待其他线程的信号
         */
        WAITING,

        /**
         *  此线程在超时阻塞等待
         */
        TIMED_WAITING,

        /**
         *  此线程已经终止
         */
        TERMINATED;
    }

    /**
     *  读取此线程的调用堆栈
     * @since 1.5
     */
    public StackTraceElement[] getStackTrace() {
        if (this != Thread.currentThread()) {
            // check for getStackTrace permission
            final SecurityManager security = System.getSecurityManager();
            if (security != null) {
                security.checkPermission(
                        SecurityConstants.GET_STACK_TRACE_PERMISSION);
            }
            // 线程已经死亡,则返回空的调用堆栈
            if (!isAlive()) {
                return EMPTY_STACK_TRACE;
            }
            final StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
            StackTraceElement[] stackTrace = stackTraceArray[0];
            // a thread that was alive during the previous isAlive call may have
            // since terminated, therefore not having a stacktrace.
            if (stackTrace == null) {
                stackTrace = EMPTY_STACK_TRACE;
            }
            return stackTrace;
        } else {
            return new Exception().getStackTrace();
        }
    }

    /**
     *  启动当前线程
     */
    public synchronized void start() {
        /**
         *  线程不是新建状态
         */
        if (threadStatus != 0) {
            throw new IllegalThreadStateException();
        }

        // 将此线程加入线程组
        group.add(this);

        boolean started = false;
        try {
            // 启动线程
            start0();
            started = true;
        } finally {
            try {
                // 如果启动失败,则将其从线程组中移除
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (final Throwable ignore) {
            }
        }
    }

    private native void start0();

    /**
     *  中断当前线程
     */
    public void interrupt() {
        if (this != Thread.currentThread()) {
            checkAccess();
        }

        synchronized (blockerLock) {
            final Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        // 中断此线程
        interrupt0();
    }

    /**
     *  阻塞等待当前线程执行完毕
     */
    public final void join() throws InterruptedException {
        join(0);
    }

    /**
     *  在指定的毫秒内阻塞等待此线程执行完毕
     *
     * @param  millis   阻塞等待的毫秒数
     */
    public final synchronized void join(long millis)
            throws InterruptedException {
        // 当前毫秒数
        final long base = System.currentTimeMillis();
        long now = 0;
        // 毫秒数非法
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }
        // 毫秒数为 0,则表示无限期阻塞等待此线程执行完毕
        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            // 线程处于存活状态
            while (isAlive()) {
                // 计算延时
                final long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                // 阻塞等待
                wait(delay);
                // 重新计算时间
                now = System.currentTimeMillis() - base;
            }
        }
    }

    /**
     *  在当前线程中执行目标任务
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章