一、Thread类

Java多线程的一种创建方式就是继承Thread类,重写run()方法实现多线程。对于Java另一种多线程的编写方式同样需要用Thread类进行方法封装。下面我将从源码角度进行Thread类内部源码的详细介绍

二、Thread类内部源码

Thread类实现了runnable接口

public
class Thread implements Runnable {
}

利用JVM实现本地注册

private static native void registerNatives();

静态代码块,实现本地注册

static {
        registerNatives();
    }

定义了一个易释放的进程名

private volatile String name;

定义了一个进程优先级

private int priority;

定义一个线程

private Thread threadQ;

下面定义了是否单步模式运行

private boolean single_step;

线程是否为守护线程

private boolean daemon = false;

调用JVM状态

private boolean stillborn = false;

定义runnable特性

private Runnable target;

定义线程组

private ThreadGroup group;

建立类加载器

private ClassLoader contextClassLoader;

继承的访问控制上下文

private AccessControlContext inheritedAccessControlContext;

定义进程初始化编号

private static int threadInitNumber;
    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }

与此线程有关的 ThreadLocal 值。该映射由 ThreadLocal 类维护。

ThreadLocal.ThreadLocalMap threadLocals = null;

与此线程有关的 InheritableThreadLocal 值。该映射由 InheritableThreadLocal 类维护。

ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

定义栈长度

private long stackSize;

定义本地事件指针

private long nativeParkEventPointer;

定义线程ID

private long tid;

用于生成线程 ID

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 MAX_PRIORITY = 10;

定义正常优先级

public final static int NORM_PRIORITY = 5;

使用JVM方法,实现当前线程

public static native Thread currentThread();

调用JVM实现进程间的相互谦让

public static native void yield();

调用JVM实现线程睡眠

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) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                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();
            }
        }

        /* 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();
        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();
    }

构建一个新进程

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

进程初始化的实现类

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

将runnable传入构建新的线程

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

线程的实现类,通过Runnable和AccessControlContext构建新的线程

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

线程的是实现类,使用ThreadGroup和Runnable构建新的线程

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

线程的是实现类,使用name构建新的线程

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

线程的是实现类,使用name和线程组构建新的线程

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

线程的是实现类,使用name和Runnable构建新的线程

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

线程的是实现类,使用ThreadGroup、name和Runnable构建新的线程

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

线程的是实现类,使用ThreadGroup、name、Runnable和栈的大小构建新的线程

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

定义线程运行方法

public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        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 */
            }
        }
    }

调用JVM实现线程运行方法

private native void start0();

定义进程运行方法

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

定义退出方式

private void exit() {
        if (group != null) {
            group.threadTerminated(this);
            group = null;
        }
        /* Aggressively null out all reference fields: see bug 4006245 */
        target = null;
        /* Speed the release of some of these resources */
        threadLocals = null;
        inheritableThreadLocals = null;
        inheritedAccessControlContext = null;
        blocker = null;
        uncaughtExceptionHandler = null;
    }

定义进程停止方法

public final void stop() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            checkAccess();
            if (this != Thread.currentThread()) {
                security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
            }
        }
        // A zero status value corresponds to "NEW", it can't change to
        // not-NEW because we hold the lock.
        if (threadStatus != 0) {
            resume(); // Wake up thread if it was suspended; no-op otherwise
        }

        // The VM can handle all thread states
        stop0(new ThreadDeath());
    }

进程停止的实现类

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();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }

判断线程是否被打断

public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

判断线程是否被打断的实现类

public boolean isInterrupted() {
        return isInterrupted(false);
    }

调用JVM来判断进程是否被打断

private native boolean isInterrupted(boolean ClearInterrupted);

调用JVM判断线程是否存在

public final native boolean isAlive();

设置线程优先级

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);
    }

让进程等待多少时间让其消亡

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;
            }
        }
    }

最多等待 ms 毫秒加上 nanos 纳秒以使该线程死亡。

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);
    }

join对外开放接口方法

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() + "," +
                            "" + "]";
        }
    }

定义类加载器

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;
    }

调用JVM实现保持锁

public static native boolean holdsLock(Object obj);

定义栈使用记录

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

返回表示此线程的堆栈转储的堆栈跟踪元素数组

public StackTraceElement[] getStackTrace() {
        if (this != Thread.currentThread()) {
            // check for getStackTrace permission
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                security.checkPermission(
                    SecurityConstants.GET_STACK_TRACE_PERMISSION);
            }
            // optimization so we do not call into the vm for threads that
            // have not yet started or have terminated
            if (!isAlive()) {
                return EMPTY_STACK_TRACE;
            }
            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 {
            // Don't need JVM help for current thread
            return (new Exception()).getStackTrace();
        }
    }

使用MAP将线程与栈进行关联

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

        // Get a snapshot of the list of all threads
        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);
            }
            // else terminated so we don't put it in the map
        }
        return m;
    }

定义运行时权限

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

定义缓冲区

private static class Caches {
        /** cache of subclass security audit results */
        static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
            new ConcurrentHashMap<>();

        /** queue for WeakReferences to audited subclasses */
        static final ReferenceQueue<Class<?>> subclassAuditsQueue =
            new ReferenceQueue<>();
    }

判断是否被CCL覆盖

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();
    }

检查本类CLASS

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();
    }

调用JVM实现栈

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

获取进程ID

public long getId() {
        return tid;
    }

枚举线程状态

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

获取线程状态信息

public State getState() {
        // get current thread state
        return sun.misc.VM.toThreadState(threadStatus);
    }

定义未获取异常接口

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;
            }
        }
    }

下面是调用JVM实现部分功能

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);