Thread源码解析 类定义 线程是程序中的执行线程.Java虚拟机允许应用程序具有多个并发运行的执行线程.Java所有多线程的实现,均通过封装Thread类实现,所以深入Thread类,对深入理解java多线程很有必要 每个线程都有一个优先级.具有较高优先级的线程优先于具有较低优先级的线程执行.每个线程可能会也可能不会被标记为守护程序.当在某个线程中运行的代码创建新的Thread对象时,新线程的优先级最初设置为与创建线程的优先级相等,并且当且仅当创建线程是守护程序时,该线程才是守护程序线程
主要变量 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 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;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 static synchronized long nextThreadID () { return ++threadSeqNumber; } private volatile int threadStatus = 0 ;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 ;
构造方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 public Thread () { init(null , null , "Thread-" + nextThreadNum(), 0 ); } public Thread (Runnable target) { init(null , target, "Thread-" + nextThreadNum(), 0 ); } 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); }
内部类 安全审核结果的缓存类Caches 1 2 3 4 5 6 7 8 9 10 private static class Caches { static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits = new ConcurrentHashMap<>(); static final ReferenceQueue<Class<?>> subclassAuditsQueue = new ReferenceQueue<>(); }
线程状态枚举类 State 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public enum State { NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED; }
主要方法 Native方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public static native Thread currentThread () ;public static native void yield () ;public static native void sleep (long millis) throws InterruptedException ;private native void start0 () ;private native boolean isInterrupted (boolean ClearInterrupted) ;public final native boolean isAlive () ;public static native boolean holdsLock (Object obj) ;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) ;
线程初始化:init 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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(); }
线程睡眠:sleep 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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); }
线程启动:start 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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) { } } }
线程运行:run 1 2 3 4 5 6 7 8 9 10 11 12 13 @Override public void run () { if (target != null ) { target.run(); } }
线程退出:exit 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 private void exit () { if (group != null ) { group.threadTerminated(this ); group = null ; } target = null ; threadLocals = null ; inheritableThreadLocals = null ; inheritedAccessControlContext = null ; blocker = null ; uncaughtExceptionHandler = null ; }
线程中断:interrupt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public void interrupt () { if (this != Thread.currentThread()) checkAccess(); synchronized (blockerLock) { Interruptible b = blocker; if (b != null ) { interrupt0(); b.interrupt(this ); return ; } } interrupt0(); } public static boolean interrupted () { return currentThread().isInterrupted(true ); } public boolean isInterrupted () { return isInterrupted(false ); }
线程等待:join 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 ); }
守护线程:daemon 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public final void setDaemon (boolean on) { checkAccess(); if (isAlive()) { throw new IllegalThreadStateException(); } daemon = on; } public final boolean isDaemon () { return daemon; }
线程优先级:priority 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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; }
线程名称 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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; }
线程组 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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); }
dumpstack 1 2 3 4 5 6 public static void dumpStack () { new Exception("Stack trace" ).printStackTrace(); }
checkAccess 1 2 3 4 5 6 7 8 9 10 11 public final void checkAccess () { SecurityManager security = System.getSecurityManager(); if (security != null ) { security.checkAccess(this ); } }
ContextClassLoader 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @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; }
线程的堆栈转储 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 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; } static void processQueue (ReferenceQueue<Class<?>> queue, ConcurrentMap<? extends WeakReference<Class<?>>, ?> map) { Reference<? extends Class<?>> ref; while ((ref = queue.poll()) != null ) { map.remove(ref); } }
CCLOverridden验证 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION = new RuntimePermission("enableContextClassLoaderOverride" );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(); }
线程id、线程状态 1 2 3 4 5 6 7 8 9 10 public long getId () { return tid; } public State getState () { return sun.misc.VM.toThreadState(threadStatus); }