1. 程式人生 > >11 java原始碼解析-Thread(草稿)

11 java原始碼解析-Thread(草稿)

1類的宣告

public
class Thread implements Runnable 
  • 實現了Runnable介面
  • 在程式開發中只要是多執行緒肯定永遠以實現Runnable介面為主。

1.1Runnable 說明

public interface Runnable {
    public abstract void run();
}

只有一個run的方法。

2常用屬性

 private volatile String name;  /*執行緒名*/
 private int            priority; /* 優先順序*/

 
  /* Whether or not to single_step this thread. */
    private boolean     single_step;/*是否單步執行*/

    /* Whether or not the thread is a daemon thread. */
    private boolean     daemon = false;/*是否守護執行緒*/

    /* JVM state */
    private boolean     stillborn = false;/*虛擬機器狀態*/

    /* What will be run. */
    private Runnable target;/*將會被執行的runnable*/

    /* The group of this thread */
    private ThreadGroup group;/*執行緒組*/

    /* The context ClassLoader for this thread *//**/
    private ClassLoader contextClassLoader;

    /* The inherited AccessControlContext of this thread */
    private AccessControlContext inheritedAccessControlContext;

    /* For autonumbering anonymous threads. */
    private static int threadInitNumber;/*執行緒的自動編號*/
    private static synchronized int nextThreadNum() {/*-----------------------------------------1*/
        return threadInitNumber++;
    }

    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

    /*
     * The requested stack size for this thread, or 0 if the creator did
     * not specify a stack size.  It is up to the VM to do whatever it
     * likes with this number; some VMs will ignore it.
     */
    private long stackSize;

    /*
     * JVM-private state that persists after native thread termination.
     */
    private long nativeParkEventPointer;

    /*
     * Thread ID
     */
    private long tid;/*執行緒id,每個執行緒都會專屬的id*/

    /* For generating thread ID */
    private static long threadSeqNumber;

    /* Java thread status for tools,
     * initialized to indicate thread 'not yet started'
     */

    private volatile int threadStatus = 0;/*執行緒狀態,1.8新加的,預設是啟動狀態*/


    private static synchronized long nextThreadID() { /*下個執行緒id*/
        return ++threadSeqNumber;
    }

    /**
     * The argument supplied to the current call to
     * java.util.concurrent.locks.LockSupport.park.
     * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
     * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
     */
    volatile Object parkBlocker;

    /* The object in which this thread is blocked in an interruptible I/O
     * operation, if any.  The blocker's interrupt method should be invoked
     * after setting this thread's interrupt status.
     */
    private volatile Interruptible blocker;
    private final Object blockerLock = new Object();

    /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
     */
    void blockedOn(Interruptible b) {
        synchronized (blockerLock) {
            blocker = b;
        }
    }

    /**
     * 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;/*最高優先順序*/

    public enum State {
 
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
 
      }

 
  • Runable 個人感覺就像汽車裡的貨物,而Thread就像汽車
  • 1處這個方法有 synchronized 修飾,是執行緒安全的
  • 執行緒六狀態:
  • NEW
  • 建立後未分配資源的狀態,沒有start的執行緒
  • RUNNABLE
  • 可執行。一旦呼叫start()方法,執行緒進入Runnable狀態,此時,該執行緒可能在執行,也可能沒有執行。這取決於作業系統給執行緒提供的執行的時間。
  • 執行緒被分配完資源後,便進入待準備狀態,可執行,等待cpu的執行
  • BLOCKED
  • 被阻塞。當一個執行緒獲取一個內部的物件鎖,而這個鎖被其他執行緒持有,則該執行緒進入阻塞狀態。當所有執行緒釋放掉該鎖,且執行緒排程器允許該執行緒持有這個物件鎖時,該執行緒進入到非阻塞狀態。
  • 被同步塊阻塞或者io阻塞
  • WAITING
  • 等待,等待被別人喚醒
  • TIMED_WAITING
  • 時間等待,睡夠時間了,自己就起來了。
  • TERMINATED
  • 被終止。一般有兩種情況:run()方法正常執行完畢而正常死亡。另一種情況是:沒有捕獲的異常終止了run()方法而意外死亡。
  • 正常執行完畢,或者異常中斷

3建構函式

public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }

  
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

   
    Thread(Runnable target, AccessControlContext acc) {
        init(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
    }

  
    public Thread(ThreadGroup group, Runnable target) {
        init(group, target, "Thread-" + nextThreadNum(), 0);
    }

  
    public Thread(String name) {
        init(null, null, name, 0);
    }

    
    public Thread(ThreadGroup group, String name) {
        init(group, null, name, 0);
    }

   
    public Thread(Runnable target, String name) {
        init(null, target, name, 0);
    }

    public Thread(ThreadGroup group, Runnable target, String name) {
        init(group, target, name, 0);
    }

   
    public Thread(ThreadGroup group, Runnable target, String name,
                  long stackSize) {
        init(group, target, name, stackSize);
    }

可以看出,執行緒呼叫的都是 init(group, target, name, stackSize);方法

init(group, target, name, stackSize)

 private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null, true);
    }

init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc,boolean inheritThreadLocals)

  • g 執行緒組
  • target 要執行的繼承Runnable介面的類的物件
  • name 執行緒的名字
  • stacksize 申請的堆的大小
 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();/*-------------------------1*/
        SecurityManager security = System.getSecurityManager();/*-------------------------2*/
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {/*-------------------------3*/
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();/*-------------------------4*/
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();/*-------------------------5*/
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }
  • 1處的意思是後去呼叫這個執行緒物件的執行緒
  • 2處的意思是獲取系統的安全管理
  • 此處解釋原文如下 if a security manager has already been established for the current application, then that security manager is returned; otherwise, null is returned.
  • 如果系統設定了安全管理器,這裡就會返回,如果沒有就會返回null
  • 3處的意思是如果安全管理不為空,那麼返回適當的執行緒組
  • 4處的意思是如果安全管理器對執行緒組沒要求,那麼返回呼叫這個執行緒物件的執行緒組。