thread 源码分析

来源:互联网 发布:mysql 复合主键怎么写 编辑:程序博客网 时间:2024/05/20 23:03
线程是程序的一个执行流程,Java虚拟机允许多个线程同时并发执行。

1. 构造方法
Java代码  收藏代码
  1. public Thread() {  
  2.     init(nullnull"Thread-" + nextThreadNum(), 0);  
  3. }  
  4.   
  5. // target - 任务  
  6. public Thread(Runnable target) {  
  7.     init(null, target, "Thread-" + nextThreadNum(), 0);  
  8. }  
  9.   
  10. // group - 线程组,target - 任务  
  11. public Thread(ThreadGroup group, Runnable target) {  
  12.     init(group, target, "Thread-" + nextThreadNum(), 0);  
  13. }  
  14.   
  15. // name - 线程名称  
  16. public Thread(String name) {  
  17.     init(nullnull, name, 0);  
  18. }  
  19.   
  20. // group - 线程组,name - 线程名称  
  21. public Thread(ThreadGroup group, String name) {  
  22.     init(group, null, name, 0);  
  23. }  
  24.   
  25. // target - 任务,name - 线程名称  
  26. public Thread(Runnable target, String name) {  
  27.     init(null, target, name, 0);  
  28. }  
  29.   
  30. // group - 线程组,target - 任务,name - 线程名称  
  31. public Thread(ThreadGroup group, Runnable target, String name) {  
  32.     init(group, target, name, 0);  
  33. }  
  34.   
  35. // group - 线程组,target - 任务,name - 线程名称, stackSize - 栈大小  
  36. // 这里的stackSize只是提供一个参考值,和平台相关,JVM根据情况会做适当的调整。  
  37. // stackSize大一些,线程就会不容易抛StackOverflowError。  
  38. // stackSize小一些,多个线程并发执行不容易抛OutOfMemoryError。  
  39. // 栈大小,最大递归深度和并发水平是和平台相关的。  
  40. public Thread(ThreadGroup group, Runnable target, String name,  
  41.                  long stackSize) {  
  42.     init(group, target, name, stackSize);  
  43. }  


2. 线程启动
Java代码  收藏代码
  1. public synchronized void start() {  
  2.     if (threadStatus != 0 || this != me)  
  3.         throw new IllegalThreadStateException();  
  4.     group.add(this);  
  5.     start0();  
  6.     if (stopBeforeStart) {  
  7.         stop0(throwableFromStop);  
  8.     }  
  9. }  
  10.   
  11. private native void start0();  


3. 任务执行

一般由JVM来调用该方法,也可以手动调用。

a. 如果子类覆盖了run()方法,则调用子类的run()
b. 如果a不成立:
   b1. 指定了target,则调用target的run()
   b2. 没有指定target,该方法不做任何事并返回
Java代码  收藏代码
  1. public void run() {  
  2.     if (target != null) {  
  3.         target.run();  
  4.     }  
  5. }  


所以,下面MyThread的run方法会执行:
Java代码  收藏代码
  1. public class MyThread extends Thread {  
  2.     public void run() {  
  3.         System.out.println("MyThread.run()");  
  4.     }  
  5. }  
  6.   
  7. new MyThread(new Runnable() {  
  8.     public void run() {  
  9.         System.out.println("Runnable.run()");  
  10.     }  
  11. }).start();  


4. 清理工作

由系统来调用该方法,在线程退出之前清理分配的资源。
Java代码  收藏代码
  1. private void exit() {  
  2.     if (group != null) {  
  3.         group.remove(this);  
  4.         group = null;  
  5.     }  
  6.   
  7.     target = null;  
  8.     threadLocals = null;  
  9.     inheritableThreadLocals = null;  
  10.     inheritedAccessControlContext = null;  
  11.     blocker = null;  
  12.     uncaughtExceptionHandler = null;  
  13. }  


5. yield方法

使当前执行线程暂停一会,让其它线程得以执行。只是临时让出时间片,不会释放拥有的锁。
Java代码  收藏代码
  1. public static native void yield();  


6. sleep方法

使当前执行线程休眠指定的时间,不释放持有的锁。
Java代码  收藏代码
  1. public static native void sleep(long millis) throws InterruptedException;  
  2.   
  3. public static void sleep(long millis, int nanos)   
  4.     throws InterruptedException {  
  5.     if (millis < 0) {  
  6.         throw new IllegalArgumentException("timeout value is negative");  
  7.     }  
  8.   
  9.     if (nanos < 0 || nanos > 999999) {  
  10.         throw new IllegalArgumentException(  
  11.             "nanosecond timeout value out of range");  
  12.     }  
  13.   
  14.     if (nanos >= 500000 || (nanos != 0 && millis == 0)) { // 纳秒四舍五入,或者毫秒为0且纳秒不为0时  
  15.         millis++;  
  16.     }  
  17.   
  18.     sleep(millis);  
  19. }  


7. join方法

等待该线程执行,直到超时或者终止。

可以作为线程通信的一种方式:A线程调用B线程的join方法(阻塞),等待B完成后再往下执行。

Java代码  收藏代码
  1. public final synchronized void join(long millis)   
  2.     throws InterruptedException {  
  3.     long base = System.currentTimeMillis();  
  4.     long now = 0;  
  5.   
  6.     if (millis < 0) {  
  7.         throw new IllegalArgumentException("timeout value is negative");  
  8.     }  
  9.   
  10.     if (millis == 0) { // 0代表没有时间限制  
  11.         while (isAlive()) {  
  12.             wait(0); // 无限期的等待  
  13.         }  
  14.     } else {  
  15.         while (isAlive()) {  
  16.             long delay = millis - now;  
  17.             if (delay <= 0) {  
  18.                 break;  
  19.             }  
  20.             wait(delay); // 有限期的等待  
  21.             now = System.currentTimeMillis() - base;  
  22.         }  
  23.     }  
  24. }  
  25.   
  26. public final synchronized void join(long millis, int nanos)   
  27.     throws InterruptedException {  
  28.   
  29.     if (millis < 0) {  
  30.         throw new IllegalArgumentException("timeout value is negative");  
  31.     }  
  32.   
  33.     if (nanos < 0 || nanos > 999999) {  
  34.         throw new IllegalArgumentException(  
  35.             "nanosecond timeout value out of range");  
  36.     }  
  37.   
  38.     if (nanos >= 500000 || (nanos != 0 && millis == 0)) { // 纳秒四舍五入,或者毫秒为0且纳秒不为0时  
  39.         millis++;  
  40.     }  
  41.   
  42.     join(millis);  
  43. }  
  44.   
  45. public final void join() throws InterruptedException {  
  46.     join(0);  
  47. }  


8. 中断
Java代码  收藏代码
  1. public void interrupt() {  
  2.     if (this != Thread.currentThread())  
  3.         checkAccess();  
  4.   
  5.     synchronized (blockerLock) {  
  6.         Interruptible b = blocker;  
  7.         if (b != null) {  
  8.             interrupt0();       // Just to set the interrupt flag  
  9.             b.interrupt();  
  10.             return;  
  11.         }  
  12.     }  
  13.     interrupt0();  
  14. }  
  15.   
  16. // 静态方法:查看当前线程是否中断,并且清除中断标志。  
  17. public static boolean interrupted() {  
  18.     return currentThread().isInterrupted(true);  
  19. }  
  20.   
  21. // 查看该线程是否中断,但不清除中断标志。  
  22. public boolean isInterrupted() {  
  23.     return isInterrupted(false);  
  24. }  
  25.   
  26. private native boolean isInterrupted(boolean ClearInterrupted);  


9. 守护/普通进程

JVM有很多守护进程:如垃圾回收线程等。没有前台(Non-Daemon)线程时,JVM会退出。

Java代码  收藏代码
  1. public final void setDaemon(boolean on) {  
  2.     checkAccess();  
  3.     if (isAlive()) {  
  4.         throw new IllegalThreadStateException();  
  5.     }  
  6.     daemon = on;  
  7. }  


10. 上下文类加载器
Java代码  收藏代码
  1. public ClassLoader getContextClassLoader() {  
  2.     if (contextClassLoader == null)  
  3.         return null;  
  4.     SecurityManager sm = System.getSecurityManager();  
  5.     if (sm != null) {  
  6.         ClassLoader ccl = ClassLoader.getCallerClassLoader(); // 调用者的类加载器  
  7.         if (ccl != null && ccl != contextClassLoader &&   
  8.             !contextClassLoader.isAncestor(ccl)) { // 调用者得类加载器不为空,且不和该线程的类加载器相同,也不是该类加载器的祖先时  
  9.             sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);  
  10.         }  
  11.     }  
  12.     return contextClassLoader;  
  13. }  
  14.   
  15. public void setContextClassLoader(ClassLoader cl) {  
  16.     SecurityManager sm = System.getSecurityManager();  
  17.     if (sm != null) {  
  18.         sm.checkPermission(new RuntimePermission("setContextClassLoader"));  
  19.     }  
  20.     contextClassLoader = cl;  
  21. }  


11. 线程的优先级
Java代码  收藏代码
  1. // 最小的优先级  
  2. public final static int MIN_PRIORITY = 1;  
  3.   
  4. // 正常的优先级  
  5. public final static int NORM_PRIORITY = 5;  
  6.   
  7. // 最大的优先级  
  8. public final static int MAX_PRIORITY = 10;  
  9.   
  10. public final void setPriority(int newPriority) {  
  11.     ThreadGroup g;  
  12.     checkAccess();  
  13.     if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {  
  14.         throw new IllegalArgumentException();  
  15.     }  
  16.     if((g = getThreadGroup()) != null) {  
  17.         if (newPriority > g.getMaxPriority()) {  
  18.             newPriority = g.getMaxPriority();  
  19.         }  
  20.         setPriority0(priority = newPriority);  
  21.     }  
  22. }  

a. 线程的优先级在不同的系统平台上,对应的系统优先级会不同;可能多个优先级对应同一个系统优先级。

b. 优先级高的线程并不一定会优先执行,这个由JVM来解译并向系统提供参考。

12. 线程的状态

Java代码  收藏代码
  1. public enum State {  
  2.     // 新建的线程,还没调用start()方法  
  3.     NEW,  
  4.   
  5.     // 可以运行,需要等到其它资源(如CPU)就绪才能运行  
  6.     RUNNABLE,  
  7.   
  8.     // 线程调用wait()后等待内置锁进入同步块或方法  
  9.     BLOCKED,  
  10.   
  11.     // 在调用无参的wait(),Thread.join()或LockSupport.lock()方法后进入等待状态  
  12.     WAITING,  
  13.   
  14.     // 调用Thread.sleep(), 有时间参数的wait(), 有时间参数的Thread.join(), LockSupport.parkNanos或LockSupport.parkUtil方法后进行有期限的等待状态  
  15.     TIMED_WAITING,  
  16.   
  17.     // 执行完毕的线程状态  
  18.     TERMINATED;  
  19. }  
  20.   
  21. public State getState() {  
  22.     // get current thread state  
  23.     return sun.misc.VM.toThreadState(threadStatus);  
  24. }  


13. 未检查异常处理器
Java代码  收藏代码
  1. public interface UncaughtExceptionHandler {   
  2.     void uncaughtException(Thread t, Throwable e);  
  3. }  
  4.   
  5. private volatile UncaughtExceptionHandler uncaughtExceptionHandler;  
  6.   
  7. private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;  
  8.   
  9. // 设置线程默认的未检查异常处理器  
  10. public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {  
  11.     SecurityManager sm = System.getSecurityManager();  
  12.     if (sm != null) {  
  13.         sm.checkPermission(  
  14.             new RuntimePermission("setDefaultUncaughtExceptionHandler")  
  15.         );  
  16.     }  
  17.   
  18.     defaultUncaughtExceptionHandler = eh;  
  19. }  
  20.   
  21. public UncaughtExceptionHandler getUncaughtExceptionHandler() {   
  22.     return uncaughtExceptionHandler != null ?  
  23.         uncaughtExceptionHandler : group;  
  24. }  
  25.   
  26. public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {   
  27.     checkAccess();  
  28.     uncaughtExceptionHandler = eh;  
  29. }  
  30.   
  31. // 只由JVM调用  
  32. private void dispatchUncaughtException(Throwable e) {  
  33.     getUncaughtExceptionHandler().uncaughtException(this, e);  
  34. }  
分享到:
ScheduledExecutorService 源码分析 |ExecutorService 分析
  • 2013-03-27 11:40
  • 浏览 1239
  • 评论(0)
  • 分类:编程语言
  • 相关推荐

0 0