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();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章