Thread源碼剖析

使用

  • 查看線程名:Thread.currenThread().getName();一般來說,主線程叫做main其他線程是Thread-x

  • 修改線程名:setName(String name)

  • 守護線程是爲其他線程服務的

    • 垃圾回收線程就是守護線程
    • 特點:當別的用戶線程執行完了,虛擬機就會退出,守護線程也就會被停止掉了。
    • 使用方法setDaemon(boolean on )在線程啓動前設置爲守護線程
    • 守護線程不要訪問共享資源(數據庫、文件等),因爲它可能在任何時候結束掉
    • 守護線程中產生的新線程也是守護線程。
  • 優先級線程:線程優先級高,僅僅表示線程獲取的CPu時間片的機率高,但這不是一個確定的因素(高度依賴於操作系統)

  • 線程的生命週期

    點擊查看源網頁

  • sleep方法:會進入計時等待狀態、等時間到了,進入的是就緒狀態而非運行狀態。

  • yield方法:先讓別的線程執行,但是不確保真正讓出。

  • join方法:會等待該線程執行完畢後才執行別的線程。

  • interrupt方法:請求終止線程,不會真正停止一個線程,只是告訴它要結束了,想讓線程自己來終止,具體中斷還是繼續執行應該由被通知的線程自己處理。

    • 方法中另外兩個方法(檢查該線程是否被中斷):
      • 靜態方法interrupted()——會清除中斷標誌位
      • 實例方法isInterrupted()——不會清楚中斷標誌位
    • stop和interrupt區別
      • stop:可以讓一個線程A終止掉另一個線程B,太暴力,且過時
        • 被終止的線程B會立即釋放鎖,這可能會讓對象處於不一致的狀態中
        • 線程A也不知道B什麼時候能夠被終止掉
      • interrupt:並不是要真正終止掉當前線程,僅僅是設置了一箇中斷標誌。這個中斷標誌可以給我們用來判斷什麼時候該幹什麼活,什麼時候中斷由我們自己來決定,這樣可以安全地終止線程。
        • 此方法根本不會對線程的狀態造成影響,它僅僅設置了一個標誌位

源碼

package java.lang;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.PrivilegedAction;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.LockSupport;
import sun.nio.ch.Interruptible;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import sun.security.util.SecurityConstants;

public
class Thread implements Runnable {
    
    private static native void registerNatives();
    static {
        registerNatives();
    }

    private volatile String name;
    private int            priority;
    private Thread         threadQ;
    private long           eetop;

   
    private boolean     single_step;

   
    private boolean     daemon = false;

 
    private boolean     stillborn = false;

   
    private Runnable target;

  
    private ThreadGroup group;

   
    private ClassLoader contextClassLoader;

   
    private AccessControlContext inheritedAccessControlContext;

    
    private static int threadInitNumber;
    //從0開始加
    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }

    
    ThreadLocal.ThreadLocalMap threadLocals = null;

    
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

    
    private long stackSize;

   
    private long nativeParkEventPointer;

   
    private long tid;

   
    private static long threadSeqNumber;

    
    private volatile int threadStatus = 0;


    private static synchronized long nextThreadID() {
        return ++threadSeqNumber;
    }


    volatile Object parkBlocker;


    private volatile Interruptible blocker;
    private final Object blockerLock = new Object();


    void blockedOn(Interruptible b) {
        synchronized (blockerLock) {
            blocker = b;
        }
    }
	//最低優先級
    public final static int MIN_PRIORITY = 1;
	//默認優先級
    public final static int NORM_PRIORITY = 5;
	//最高優先級
    public final static int MAX_PRIORITY = 10;


    public static native Thread currentThread();


    public static native void yield();


    public static native void sleep(long millis) throws InterruptedException;


    public static void sleep(long millis, int nanos)
    throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        sleep(millis);
    }

   	/*
   	 *初始化線程
   	 *
   	 */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null, true);
    }

   
    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) {
            
            if (security != null) {
                g = security.getThreadGroup();
            }

          
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

      
        g.checkAccess();

        
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        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);
        
        this.stackSize = stackSize;

       
        tid = nextThreadID();
    }

   
    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

   	//命名
    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);
    }

    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 (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();

   
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

    
    private void exit() {
        if (group != null) {
            group.threadTerminated(this);
            group = null;
        }
        
        target = null;
       
        threadLocals = null;
        inheritableThreadLocals = null;
        inheritedAccessControlContext = null;
        blocker = null;
        uncaughtExceptionHandler = null;
    }

    
    @Deprecated
    public final void stop() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            checkAccess();
            if (this != Thread.currentThread()) {
                security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
            }
        }
       
        if (threadStatus != 0) {
            resume(); 
        }

        stop0(new ThreadDeath());
    }

    
    @Deprecated
    public final synchronized void stop(Throwable obj) {
        throw new UnsupportedOperationException();
    }
	/*
	 * 中斷當前線程
	 * 只能自己調用中斷的方法,不然會拋出安全異常
	 */
    public void interrupt() {
        //檢查是否有權限
        if (this != Thread.currentThread())
            checkAccess();

        synchronized (blockerLock) {
            //看看是不是阻塞的線程調用
            interruptible b = blocker;
            if (b != null) {
                interrupt0();
                //如果是,拋出異常,將中斷標誌位改了(改爲false)一般我們會再catch中再次修改
                b.interrupt(this);
                return;
            }
        }
        //如果很順利,就可以修改到標誌位(沒有進入if)
        interrupt0();
    }
	//該方法會清除中斷標誌位
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
	//該方法不會影響中斷標誌位
    public boolean isInterrupted() {
        return isInterrupted(false);
    }

    private native boolean isInterrupted(boolean ClearInterrupted);

    @Deprecated
    public void destroy() {
        throw new NoSuchMethodError();
    }

    public final native boolean isAlive();

    @Deprecated
    public final void suspend() {
        checkAccess();
        suspend0();
    }

    @Deprecated
    public final void resume() {
        checkAccess();
        resume0();
    }
	//優先級
    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);
        }
    }

    public final int getPriority() {
        return priority;
    }
	//設置線程名
    public final synchronized void setName(String name) {
        //檢查是否有權限
        checkAccess();
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;
        if (threadStatus != 0) {
            setNativeName(name);
        }
    }

    public final String getName() {
        return name;
    }

    public final ThreadGroup getThreadGroup() {
        return group;
    }

    public static int activeCount() {
        return currentThread().getThreadGroup().activeCount();
    }

    public static int enumerate(Thread tarray[]) {
        return currentThread().getThreadGroup().enumerate(tarray);
    }

    @Deprecated
    public native int countStackFrames();

    public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

    public final synchronized void join(long millis, int nanos)
    throws InterruptedException {

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        join(millis);
    }

    public final void join() throws InterruptedException {
        join(0);
    }

    public static void dumpStack() {
        new Exception("Stack trace").printStackTrace();
    }
	//如果啓動了再設置守護線程,會拋出異常
    public final void setDaemon(boolean on) {
        checkAccess();
        if (isAlive()) {
            throw new IllegalThreadStateException();
        }
        daemon = on;
    }

    public final boolean isDaemon() {
        return daemon;
    }
	
    public final void checkAccess() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkAccess(this);
        }
    }

    public String toString() {
        ThreadGroup group = getThreadGroup();
        if (group != null) {
            return "Thread[" + getName() + "," + getPriority() + "," +
                           group.getName() + "]";
        } else {
            return "Thread[" + getName() + "," + getPriority() + "," +
                            "" + "]";
        }
    }

    @CallerSensitive
    public ClassLoader getContextClassLoader() {
        if (contextClassLoader == null)
            return null;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            ClassLoader.checkClassLoaderPermission(contextClassLoader,
                                                   Reflection.getCallerClass());
        }
        return contextClassLoader;
    }

    public void setContextClassLoader(ClassLoader cl) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new RuntimePermission("setContextClassLoader"));
        }
        contextClassLoader = cl;
    }

    public static native boolean holdsLock(Object obj);

    private static final StackTraceElement[] EMPTY_STACK_TRACE
        = new StackTraceElement[0];

    public StackTraceElement[] getStackTrace() {
        if (this != Thread.currentThread()) {
          
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                security.checkPermission(
                    SecurityConstants.GET_STACK_TRACE_PERMISSION);
            }
           
            if (!isAlive()) {
                return EMPTY_STACK_TRACE;
            }
            StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
            StackTraceElement[] stackTrace = stackTraceArray[0];
            
            if (stackTrace == null) {
                stackTrace = EMPTY_STACK_TRACE;
            }
            return stackTrace;
        } else {
            
            return (new Exception()).getStackTrace();
        }
    }

    public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
        
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkPermission(
                SecurityConstants.GET_STACK_TRACE_PERMISSION);
            security.checkPermission(
                SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
        }

      
        Thread[] threads = getThreads();
        StackTraceElement[][] traces = dumpThreads(threads);
        Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
        for (int i = 0; i < threads.length; i++) {
            StackTraceElement[] stackTrace = traces[i];
            if (stackTrace != null) {
                m.put(threads[i], stackTrace);
            }
           
        }
        return m;
    }


    private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
                    new RuntimePermission("enableContextClassLoaderOverride");

  
    private static class Caches {
      
        static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
            new ConcurrentHashMap<>();

       
        static final ReferenceQueue<Class<?>> subclassAuditsQueue =
            new ReferenceQueue<>();
    }

    private static boolean isCCLOverridden(Class<?> cl) {
        if (cl == Thread.class)
            return false;

        processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
        WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
        Boolean result = Caches.subclassAudits.get(key);
        if (result == null) {
            result = Boolean.valueOf(auditSubclass(cl));
            Caches.subclassAudits.putIfAbsent(key, result);
        }

        return result.booleanValue();
    }

    private static boolean auditSubclass(final Class<?> subcl) {
        Boolean result = AccessController.doPrivileged(
            new PrivilegedAction<Boolean>() {
                public Boolean run() {
                    for (Class<?> cl = subcl;
                         cl != Thread.class;
                         cl = cl.getSuperclass())
                    {
                        try {
                            cl.getDeclaredMethod("getContextClassLoader", new Class<?>[0]);
                            return Boolean.TRUE;
                        } catch (NoSuchMethodException ex) {
                        }
                        try {
                            Class<?>[] params = {ClassLoader.class};
                            cl.getDeclaredMethod("setContextClassLoader", params);
                            return Boolean.TRUE;
                        } catch (NoSuchMethodException ex) {
                        }
                    }
                    return Boolean.FALSE;
                }
            }
        );
        return result.booleanValue();
    }

    private native static StackTraceElement[][] dumpThreads(Thread[] threads);
    private native static Thread[] getThreads();

    
    public long getId() {
        return tid;
    }

    public enum State {
      
        NEW,

      
        RUNNABLE,

     
        BLOCKED,

        WAITING,

        
        TIMED_WAITING,

       
        TERMINATED;
    }

   
    public State getState() {
        
        return sun.misc.VM.toThreadState(threadStatus);
    }

  
    @FunctionalInterface
    public interface UncaughtExceptionHandler {
        
        void uncaughtException(Thread t, Throwable e);
    }

    
    private volatile UncaughtExceptionHandler uncaughtExceptionHandler;


    private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;

    
    public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(
                new RuntimePermission("setDefaultUncaughtExceptionHandler")
                    );
        }

         defaultUncaughtExceptionHandler = eh;
     }

   
    public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
        return defaultUncaughtExceptionHandler;
    }

    
    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
        return uncaughtExceptionHandler != null ?
            uncaughtExceptionHandler : group;
    }

 
    public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
        checkAccess();
        uncaughtExceptionHandler = eh;
    }

   
    private void dispatchUncaughtException(Throwable e) {
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }

   
    static void processQueue(ReferenceQueue<Class<?>> queue,
                             ConcurrentMap<? extends
                             WeakReference<Class<?>>, ?> map)
    {
        Reference<? extends Class<?>> ref;
        while((ref = queue.poll()) != null) {
            map.remove(ref);
        }
    }

    
    static class WeakClassKey extends WeakReference<Class<?>> {
      
        private final int hash;

        
        WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
            super(cl, refQueue);
            hash = System.identityHashCode(cl);
        }

        
        @Override
        public int hashCode() {
            return hash;
        }

       
        @Override
        public boolean equals(Object obj) {
            if (obj == this)
                return true;

            if (obj instanceof WeakClassKey) {
                Object referent = get();
                return (referent != null) &&
                       (referent == ((WeakClassKey) obj).get());
            } else {
                return false;
            }
        }
    }


    @sun.misc.Contended("tlr")
    long threadLocalRandomSeed;

   
    @sun.misc.Contended("tlr")
    int threadLocalRandomProbe;

  
    @sun.misc.Contended("tlr")
    int threadLocalRandomSecondarySeed;

   
    private native void setPriority0(int newPriority);
    private native void stop0(Object o);
    private native void suspend0();
    private native void resume0();
    private native void interrupt0();
    private native void setNativeName(String name);
}

測試實例

給線程起名字

  • 實現了Runnable的方式來實現多線程
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        //打印出當前線程的名字
        System.out.println(Thread.currentThread().getName());
    }
}

  • 測試
public class MyRunnableDemo {
    public static void main(String[] args) {
        // 創建MyRunnable類的對象
        MyRunnable my = new MyRunnable();
        // 使用帶參構造方法給線程起名字
        Thread t1 = new Thread(my,"關注我");
        Thread t2 = new Thread(my,"冢狐");
        t1.start();
        t2.start();
        // 打印出當前線程的名字
        System.out.println(Thread.currentThread().getName());
    }
}
  • 結果

守護線程

  • 設置守護線程
public class MyRunnableDemo {
    public static void main(String[] args) {
        // 創建MyRunnable類的對象
        MyRunnable my = new MyRunnable();
        // 使用帶參構造方法給線程起名字
        Thread t1 = new Thread(my,"關注我");
        Thread t2 = new Thread(my,"冢狐");
        //設置守護線程
        t2.setDaemon(true);
        t1.start();
        t2.start();
        // 打印出當前線程的名字
        System.out.println(Thread.currentThread().getName());
    }
}
  • 結果

線程1和主線程執行完了,我們的守護線程就不執行了,所以要在啓動前設置守護線程

線程停止

public class Main {
    public static void main(String[] args) {
        Main main=new Main();
        //創建線程並啓動
        Thread t=new Thread(main.runnable);
        System.out.println("This is main");
        t.start();
        try {
            // 在main線程睡個三秒鐘
            Thread.sleep(3000);
        }catch (InterruptedException e){
            System.out.println("In main");
            e.printStackTrace();
        }
        // 設置中斷
        t.interrupt();
    }
    Runnable runnable=()->{
        int i=0;
        try {
            while (i<1000){
                // 睡個半秒再執行
                Thread.sleep(500);
                System.out.println(i++);
            }
        }catch (InterruptedException e){
            // 判斷該阻塞線程是否還在
            System.out.println(Thread.currentThread().isAlive());
            // 判斷該線程的中斷標誌位狀態
            System.out.println(Thread.currentThread().isInterrupted());

            System.out.println("In Runnable");
            e.printStackTrace();
        }
    };
}
  • 結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章