AEThread只是一个简单的线程类,提供一个抽象方法runSupport 供我们重写,相必之下,AEThread2有几个改进的地方:1)加入了运行锁机制,运行线程和等待线程的结束这两个操作需要争抢运行锁,若锁未放开,则说明线程还在运行,必须等待锁的释放。2)设置了一个守护线程链表,若待创建的线程是守护线程,当链表为空时,新建一个守护线程加入表尾,否则从链表尾部取一个线程节点来使用,类似线程池。3)对于守护线程,若活跃时间超过时限,就会从守护线程链表中删除头部节点,即超时最长时间的节点。

  1. public abstract class AEThread2   
  2. {  
  3.     public static final boolean TRACE_TIMES = false;//是否跟踪线程运行时间  
  4.       
  5.     private static final int MIN_RETAINED    = 2;//守护线程最小个数  
  6.     private static final int MAX_RETAINED    = 16;//守护线程最大个数  
  7.       
  8.     private static final int THREAD_TIMEOUT_CHECK_PERIOD    = 10*1000;//线程超时检查间隔期:10秒  
  9.     private static final int THREAD_TIMEOUT                    = 60*1000;//线程超时时限:60秒   
  10.       
  11.     private static final LinkedList    daemon_threads = new LinkedList();//守护线程链表  
  12.       
  13.     private static final class JoinLock   
  14.     {  
  15.         volatile boolean released = false;//初始状态锁未放开  
  16.     }  
  17.       
  18.     private static long    last_timeout_check;//最近的超时检查时间  
  19.       
  20.     private static long    total_starts;//启动的线程总数  
  21.     private static long    total_creates;//创建的线程总数  
  22.       
  23.       
  24.     private threadWrapper    wrapper;//线程包装器(实质的线程)  
  25.       
  26.     private String name;//线程名称  
  27.     private boolean daemon;//是否守护线程  
  28.     private int priority = Thread.NORM_PRIORITY;//线程优先级  
  29.     private volatile JoinLock lock = new JoinLock();  
  30.       
  31.     public AEThread2(String    _name,boolean _daemon )  
  32.     {  
  33.         name = _name;  
  34.         daemon = _daemon;  
  35.     }  
  36.     public void start()  
  37.     {  
  38.         JoinLock currentLock = lock;  
  39.         JoinLock newLock;  
  40.           
  41.         synchronized (currentLock)  
  42.         {  
  43.             // create new lock in case this is a restart, all old .join()s will be locked on the old thread and thus released by the old thread  
  44.             if(currentLock.released)  
  45.                 newLock = lock = new JoinLock();  
  46.             else 
  47.                 newLock = currentLock;  
  48.         }  
  49.           
  50.         if ( daemon )  
  51.         {//是守护线程  
  52.             synchronized( daemon_threads )  
  53.             {  
  54.                 total_starts++;//启动的总线程数加1                  
  55.                 if ( daemon_threads.isEmpty())  
  56.                 {//若守护线程链表为空,则创建一个新线程  
  57.                     total_creates++;  
  58.                     wrapper = new threadWrapper( name, true );              
  59.                 }  
  60.                 else 
  61.                 {//从守护线程链表中移除尾部节点  
  62.                     wrapper = (threadWrapper)daemon_threads.removeLast();  
  63.                     wrapper.setName( name );  
  64.                 }  
  65.             }  
  66.         }  
  67.         else 
  68.         {//不是守护线程  
  69.           
  70.             wrapper = new threadWrapper( name, false );  
  71.         }  
  72.           
  73.         if ( priority != wrapper.getPriority() )  
  74.         {//设置线程优先级  
  75.             wrapper.setPriority( priority );  
  76.         }  
  77.           
  78.         wrapper.currentLock = newLock;//传递锁  
  79.           
  80.         wrapper.start( this, name );//真正启动线程运行  
  81.     }  
  82.       
  83.     public void setPriority(int _priority )  
  84.     {  
  85.         priority    = _priority;  
  86.         if ( wrapper != null )  
  87.         {  
  88.             wrapper.setPriority( priority );  
  89.         }  
  90.     }  
  91.       
  92.     public void setName(String    s )  
  93.     {  
  94.         name    = s;  
  95.         if ( wrapper != null )  
  96.         {  
  97.             wrapper.setName( name );  
  98.         }  
  99.     }  
  100.       
  101.     public String getName()  
  102.     {  
  103.         return( name );  
  104.     }  
  105.       
  106.     public void interrupt()  
  107.     {  
  108.         if ( wrapper == null )  
  109.         {  
  110.             throw new IllegalStateException( "Interrupted before started!" );  
  111.               
  112.         }  
  113.         else 
  114.         {  
  115.             wrapper.interrupt();//中断线程  
  116.         }  
  117.     }  
  118.       
  119.     public boolean isCurrentThread()  
  120.     {  
  121.         return( wrapper == Thread.currentThread());  
  122.     }  
  123.       
  124.     public String toString()  
  125.     {  
  126.         if ( wrapper == null )  
  127.         {  
  128.             return( name + " [daemon=" + daemon + ",priority=" + priority + "]" );  
  129.               
  130.         }  
  131.         else 
  132.         {  
  133.             return( wrapper.toString());  
  134.         }  
  135.     }  
  136.       
  137.     public abstract void run();//实质的线程函数,在包装器类中调用  
  138.       
  139.     public static boolean isOurThread(Thread thread )  
  140.     {  
  141.         return( AEThread.isOurThread( thread ));  
  142.     }  
  143.       
  144.     public static void setOurThread()  
  145.     {  
  146.         AEThread.setOurThread();  
  147.     }  
  148.       
  149.     public static void setOurThread(Thread    thread )  
  150.     {  
  151.         AEThread.setOurThread( thread );  
  152.     }  
  153.       
  154.     //实质的线程,从Thread类继承  
  155.     protected static class threadWrapper extends Thread  
  156.     {  
  157.         private AESemaphore sem;  
  158.         private AEThread2    target; //被包装的目标  
  159.         private JoinLock    currentLock;//锁  
  160.           
  161.         private long        last_active_time;//最近活跃时间  
  162.           
  163.         protected threadWrapper(String name,boolean daemon )  
  164.         {  
  165.             super( name );  
  166.             setDaemon( daemon );//设置是否守护线程  
  167.         }  
  168.           
  169.         public void run()  
  170.         {  
  171.             whiletrue )  
  172.             {  
  173.                 synchronized( currentLock )  
  174.                 {  
  175.                     try 
  176.                     {  
  177.                         if ( TRACE_TIMES )  
  178.                         {  
  179.                             long     start_time     = SystemTime.getHighPrecisionCounter();  
  180.                             long    start_cpu     = Java15Utils.getThreadCPUTime();  
  181.  
  182.                             try 
  183.                             {  
  184.                                 target.run();//实质的线程函数  
  185.  
  186.                             }  
  187.                             finally 
  188.                             {  
  189.                                 long    time_diff     = ( SystemTime.getHighPrecisionCounter() - start_time )/1000000;  
  190.                                 long    cpu_diff    = ( Java15Utils.getThreadCPUTime() - start_cpu ) / 1000000;  
  191.                                   
  192.                                 if ( cpu_diff > 10 || time_diff > 10 )  
  193.                                 {  
  194.                                     System.out.println( TimeFormatter.milliStamp() + ": Thread: " + target.getName() + ": " + cpu_diff + "/" + time_diff );  
  195.                                 }  
  196.                             }  
  197.                         }  
  198.                         else 
  199.                         {  
  200.                             target.run();  
  201.                         }  
  202.                                                   
  203.                     }  
  204.                     catch( Throwable e )  
  205.                     {  
  206.                         DebugLight.printStackTrace(e);  
  207.                           
  208.                     }  
  209.                     finally 
  210.                     {//线程运行结束  
  211.                         target = null;  
  212.                         currentLock.released = true;//释放锁  
  213.                         currentLock.notifyAll();//通知其他阻塞线程                          
  214.                     }  
  215.                 }  
  216.                                   
  217.                 if ( isInterrupted() || !Thread.currentThread().isDaemon())  
  218.                 {//中断或不是守护线程  
  219.                     break;  
  220.                       
  221.                 }  
  222.                 else 
  223.                 {//是守护线程                      
  224.                     synchronized( daemon_threads )  
  225.                     {                      
  226.                         last_active_time    = SystemTime.getCurrentTime();                          
  227.                         if (last_active_time < last_timeout_check ||last_active_time - last_timeout_check > THREAD_TIMEOUT_CHECK_PERIOD )  
  228.                         {  
  229.                             last_timeout_check    = last_active_time;  
  230.                               
  231.                             while( daemon_threads.size() > 0 && daemon_threads.size() > MIN_RETAINED )  
  232.                             {                                  
  233.                                 threadWrapper thread = (threadWrapper)daemon_threads.getFirst();//取链表头部                                  
  234.                                 long    thread_time = thread.last_active_time;                                  
  235.                                 if (last_active_time < thread_time ||last_active_time - thread_time > THREAD_TIMEOUT )  
  236.                                 {                                      
  237.                                     daemon_threads.removeFirst();//移除超时节点                                      
  238.                                     thread.retire();//被移除节点信号量释放  
  239.                                       
  240.                                 }  
  241.                                 else 
  242.                                 {                                  
  243.                                     break;  
  244.                                 }  
  245.                             }  
  246.                         }                  
  247.                         if ( daemon_threads.size() >= MAX_RETAINED )  
  248.                         {                          
  249.                             return;  
  250.                         }  
  251.                         daemon_threads.addLast( this );//将此守护节点加入守护线程链表尾部,这样头部应该是最先超时的节点  
  252.                         setName( "AEThead2:parked[" + daemon_threads.size() + "]" );                          
  253.                         // System.out.println( "AEThread2: queue=" + daemon_threads.size() + ",creates=" + total_creates + ",starts=" + total_starts );  
  254.                     }                      
  255.                     sem.reserve();//新加入节点信号量增加                      
  256.                     if ( target == null )  
  257.                     {                          
  258.                         break;  
  259.                     }  
  260.                 }  
  261.             }  
  262.         }  
  263.           
  264.         protected void start(AEThread2    _target,String        _name )  
  265.         {  
  266.             target    = _target;              
  267.             setName( _name );              
  268.             if ( sem == null )  
  269.             {                  
  270.                  sem = new AESemaphore( "AEThread2" );                   
  271.                  super.start();//启动线程               
  272.             }  
  273.             else 
  274.             {                  
  275.                 sem.release();  
  276.             }  
  277.         }  
  278.           
  279.         protected void retire()  
  280.         {              
  281.             sem.release();  
  282.         }  
  283.     }  
  284.       
  285.     public void join()  
  286.     {//等待线程结束  
  287.         JoinLock currentLock = lock;  
  288.         // sync lock will be blocked by the thread          
  289.         synchronized( currentLock )  
  290.         {              
  291.             // wait in case the thread is not running yet              
  292.             while (!currentLock.released )  
  293.             {//若锁还未释放,则说明线程还在运行,则继续等待锁的释放,                  
  294.                 try 
  295.                 {  
  296.                     currentLock.wait();                      
  297.                 }  
  298.                 catch( InterruptedException e ){}  
  299.             }  
  300.         }  
  301.     }