求助 如何监测java某个线程内存的占用情况啊?
public class Main { public static void main(String[] args) {
long start =  Runtime.getRuntime().totalMemory();
System.out.println("start : " + start);
String s = "123123123123123";
for(int i = 0; i < 20;i ++){
s += s;
}
long end =  Runtime.getRuntime().totalMemory();
System.out.println("end : " + end);
}}
这个当循环变量i很小的时候根本没有结果start = end 

解决方案 »

  1.   

    以下是一个完整的程序
    import java.util.Vector;
    import java.lang.Runnable;
    import org.apache.log4j.Logger;public class ThreadPool 
    {
        public static final int MAX_THREADS = 100; //默认最大线程数
        public static final int MAX_SPARE_THREADS = 50; //默认最大空闲线程数
        public static final int MIN_SPARE_THREADS = 10; //默认最小空闲线程数
        public static final long MONITOR_WAIT_TIME = 60 * 1000; //每隔六十秒检查一次线程池
        public static final int THREAD_MAX_ACTIVE_TIME = 5 * 60; //线程最大活动时间,缺省300秒
        
        protected Vector m_ThreadPool; //用Vector构造的线程池
        protected Vector m_BusyThreadPool; //用Vector构造的线程组,用于监控
        protected MonitorRunnable m_ThreadPoolMonitor;  //线程管理器
        protected long m_MonitorWaitTime; //线程管理器工作间隔时间    
        protected int m_MaxThreads; //最大线程数    
        protected int m_MaxSpareThreads; //最大空闲线程数
        protected int m_MinSpareThreads; //最小空闲线程数
        protected int m_CurrentThreadCount; //当前线程数
        protected int m_CurrentThreadsBusy; //当前忙的线程数
        protected boolean m_IsStopPool; //是否关闭线程池
        private   int m_ThreadIDCounter=0; //线程ID号计数器
        private   Vector m_SpareThreadID; //用Vector构造的空闲线程ID
        protected int m_ThreadMaxActiveTime;//线程最大活动时间,单位秒
        
        protected String m_ThreadPoolName="ThreadPool";
        protected Logger m_Logger; /*
     * 构造函数  
     */
        public ThreadPool(Logger logger) {
         m_Logger = logger;
            m_MaxThreads = MAX_THREADS;
            m_MaxSpareThreads = MAX_SPARE_THREADS;
            m_MinSpareThreads = MIN_SPARE_THREADS;
            m_MonitorWaitTime = MONITOR_WAIT_TIME;
            m_ThreadMaxActiveTime = THREAD_MAX_ACTIVE_TIME;
            m_CurrentThreadCount = 0;
            m_CurrentThreadsBusy = 0;
            m_IsStopPool = false;
            m_BusyThreadPool = new Vector();
            m_SpareThreadID = new Vector();
        }
    /*
     * 函数功能:开启线程池
     * 参数:无
     * 返回:无
     */
        public synchronized void start() {
         //调整线程数,避免非法设置
            adjustLimits();
            //开启最小线程数
            openThreads(m_MinSpareThreads);
            //打开线程管理
            m_ThreadPoolMonitor = new MonitorRunnable(this);
            m_Logger.info("ThreadPool start ok");
            m_Logger.info("ThreadPool MaxThreads="+m_MaxThreads+" MaxSpareThreads="+m_MaxSpareThreads+" MinSpareThreads="+m_MinSpareThreads+" MonitorWaitTime="+m_MonitorWaitTime+" ThreadMaxActiveTime="+m_ThreadMaxActiveTime);
        }
     
        public void setThreadPoolName(String threadPoolName) {
            this.m_ThreadPoolName = threadPoolName;
        }    public String getThreadPoolName() {
            return m_ThreadPoolName;
        }    public void setMaxThreads(int maxThreads) {
            this.m_MaxThreads = maxThreads;
        }    public int getMaxThreads() {
            return m_MaxThreads;
        }    public void setMinSpareThreads(int minSpareThreads) {
            this.m_MinSpareThreads = minSpareThreads;
        }    public int getMinSpareThreads() {
            return m_MinSpareThreads;
        }
        public void setMaxSpareThreads(int maxSpareThreads) {
            this.m_MaxSpareThreads = maxSpareThreads;
        }
        
        public void setThreadMaxActiveTime(int threadMaxActiveTime) {
            this.m_ThreadMaxActiveTime = threadMaxActiveTime;
        }    public int getMaxSpareThreads() {
            return m_MaxSpareThreads;
        }
     
        public void setMonitorWaitTime(long monitorWaitTime) {
            this.m_MonitorWaitTime = monitorWaitTime;
        }    public long getMonitorWaitTime() {
            return m_MonitorWaitTime;
        }    public int getCurrentThreadCount() {
            return m_CurrentThreadCount;
        }    public int getThreadMaxActiveTime() {
            return m_ThreadMaxActiveTime;
        }
        
        public boolean isFullThreads(){
         return m_CurrentThreadsBusy >= m_MaxThreads;
        }
       
        /*
         * 函数功能:添加任务
         * 参数:ThreadRunnable r
         * 返回:无
         */
        public void runIt(ThreadRunnable r) {
         //处理异常
            if (null == r) {
             m_Logger.error("ThreadPool Runnable is null");
                throw new NullPointerException("ThreadPool Runnable is null");
            }
            if (m_IsStopPool) {
             m_Logger.error("ThreadPool state is  illegal1: IsStopPool "+m_IsStopPool);
                throw new IllegalStateException("ThreadPool state is  illegal1: IsStopPool "+m_IsStopPool);
            }
            //声明线程
            ControlRunnable c = null;
            //同步
            synchronized (this) {
             fixThreadCount();
             //当前所有线程都忙的时候
                if (m_CurrentThreadsBusy == m_CurrentThreadCount) {
                 //如果还没有达到最大线程数,就继续增加
                    if (m_CurrentThreadCount < m_MaxThreads) {
                        int toOpen = m_CurrentThreadCount + m_MinSpareThreads;
                        openThreads(toOpen);
                    } else {
                        while (m_CurrentThreadsBusy == m_CurrentThreadCount) {
                            try {
                                this.wait();
                            }catch (InterruptedException e) {
                            }
                            if (0 == m_CurrentThreadCount || m_IsStopPool) {
             m_Logger.error("ThreadPool state is  illegal2: CurrentThreadCount "+m_CurrentThreadCount+" IsStopPool "+m_IsStopPool);
                                throw new IllegalStateException("ThreadPool state is  illegal2: CurrentThreadCount "+m_CurrentThreadCount+" IsStopPool "+m_IsStopPool);
                            }
                        }
                    }
                }
                //从线程池取一条线程
                c = (ControlRunnable) m_ThreadPool.lastElement();
                m_ThreadPool.removeElement(c);
                m_CurrentThreadsBusy++;
                m_BusyThreadPool.addElement(c);
            }
            //执行该任务
            c.runIt(r);
        }
       
       //关闭线程池
        public synchronized void shutdown() 
        {
            if (!m_IsStopPool) {
                m_IsStopPool = true;
                //关闭池管理
                m_ThreadPoolMonitor.terminate();
                m_ThreadPoolMonitor = null;
                //把空闲的线程都停掉
                int size = m_ThreadPool.size();
                for (int i = 0; i < size; i++) {
                    try {
                        ((ControlRunnable) (m_ThreadPool.elementAt(i))).terminate();
                    } catch (Throwable t) {
                    }
                }
                //把繁忙的线程都停掉
                size = m_BusyThreadPool.size();
                for (int i = 0; i < size; i++) {
                    try {
                        ((ControlRunnable) (m_BusyThreadPool.elementAt(i))).terminate();
                    } catch (Throwable t) {
                    }
                }
                m_CurrentThreadsBusy = m_CurrentThreadCount = 0;
                m_ThreadPool.clear();
                m_ThreadPool = null;
                m_BusyThreadPool.clear();
                m_BusyThreadPool=null;
                m_Logger.info("ThreadPool shutdown ok");
                notifyAll();
            }
        }
        
        //当空闲的线程过多的时候释放它们
      protected synchronized void checkSpareControllers() {
            if (m_IsStopPool) {
                return;
            }
            m_Logger.info("ThreadPool check: CurrentCount="+m_CurrentThreadCount+" CurrentBusy="+m_CurrentThreadsBusy+" MaxSpare="+m_MaxSpareThreads);
            if ((m_CurrentThreadCount - m_CurrentThreadsBusy) > m_MaxSpareThreads) {
                int toFree = m_CurrentThreadCount - m_CurrentThreadsBusy - m_MaxSpareThreads;
                for (int i = 0; i < toFree; i++) {
                    ControlRunnable c = (ControlRunnable) m_ThreadPool.firstElement();
                    m_ThreadPool.removeElement(c);
                    m_CurrentThreadCount--;
                    m_SpareThreadID.add(Integer.toString(c.getThreadNum()));
                    c.terminate();
                }
            }
            try{
             int busyNum = m_BusyThreadPool.size();
             m_Logger.info("BusyThreadPool check: CurrentBusy="+busyNum);
             long runtime = 0;
             Vector deadThreads = new Vector();
             for(int i=0; i<busyNum; i++) {
                    ControlRunnable c = (ControlRunnable) m_BusyThreadPool.get(i);
                    runtime = c.getRunTime()/1000;
                    m_Logger.info("BusyThreadPool check: "+c.getThreadName()+" RunTime="+runtime+"s");
                    if(runtime>m_ThreadMaxActiveTime) deadThreads.addElement(c);
             }
             //delete dead thread
             int deadNum = deadThreads.size();
             for(int i=0; i<deadNum; i++) {
                    ControlRunnable c = (ControlRunnable) deadThreads.get(i);
                    m_BusyThreadPool.removeElement(c);
                    m_CurrentThreadsBusy--;
                    m_CurrentThreadCount--;
                    c.terminate();
             }
             deadThreads.clear();
             deadThreads=null;
            }catch(Exception ex){
             m_Logger.error("BusyThreadPool check error", ex);
            }
            try{
             fixThreadCount();
            }catch(Exception ex){
             m_Logger.error("ThreadPool fix error", ex);
            }
        }
      

  2.   

      protected synchronized void fixThreadCount() 
        {
         int spareNum = m_ThreadPool.size();
         if( m_CurrentThreadsBusy != m_BusyThreadPool.size() ) {
         m_CurrentThreadsBusy = m_BusyThreadPool.size();
         m_Logger.info("ThreadPool fix: CurrentThreadsBusy=>"+m_CurrentThreadsBusy);
         }
         if( spareNum != (m_CurrentThreadCount - m_CurrentThreadsBusy)){
         m_CurrentThreadCount = spareNum + m_CurrentThreadsBusy;
         m_Logger.info("ThreadPool fix: CurrentThreadCount=>"+m_CurrentThreadCount);
         }
        }
        
        //任务完成之后把线程放回线程池
        protected synchronized void returnController(ControlRunnable c) {
            if (0 == m_CurrentThreadCount || m_IsStopPool) {
                c.terminate();
                return;
            }
            m_CurrentThreadsBusy--;
            
            m_BusyThreadPool.removeElement(c);
            m_ThreadPool.addElement(c);
            notify();
        }
        
        protected synchronized void notifyThreadEnd() {
            m_CurrentThreadsBusy--;
            m_CurrentThreadCount--;
            notify();
            openThreads(m_MinSpareThreads);
        }
        
        //调整线程数
        protected void adjustLimits() {
            if (m_MaxThreads <= 0) {
                m_MaxThreads = MAX_THREADS;
            }
            if (m_MaxSpareThreads >= m_MaxThreads) {
                m_MaxSpareThreads = m_MaxThreads;
            }
            if (m_MaxSpareThreads <= 0) {
                if (1 == m_MaxThreads) {
                    m_MaxSpareThreads = 1;
                } else {
                    m_MaxSpareThreads = m_MaxThreads / 2;
                }
            }
            if (m_MinSpareThreads > m_MaxSpareThreads) {
                m_MinSpareThreads = m_MaxSpareThreads;
            }
            if (m_MinSpareThreads <= 0) {
                if (1 == m_MaxSpareThreads) {
                    m_MinSpareThreads = 1;
                } else {
                    m_MinSpareThreads = m_MaxSpareThreads / 2;
                }
            }
        } //开线程数
        protected void openThreads(int toOpen) {
            if (toOpen > m_MaxThreads) {
                toOpen = m_MaxThreads;
            }
            if (0 == m_CurrentThreadCount) {
                m_ThreadPool = new Vector(toOpen);
            }
            for (int i = m_CurrentThreadCount; i < toOpen; i++) {
             int threadNum = 0;
             if(m_SpareThreadID.size()>0){
             Object num = m_SpareThreadID.firstElement();
             m_SpareThreadID.remove(num);
             threadNum = Integer.parseInt(num.toString());
             //this.log(1, "openThreads threadNum="+threadNum);
             }else{
             m_ThreadIDCounter++;
             threadNum = m_ThreadIDCounter;
             }
                m_ThreadPool.addElement(new ControlRunnable(this, threadNum));
            }
            m_CurrentThreadCount = toOpen;
        }        //记录日志
        protected void log(int level, String mess) {
            if(level==0) m_Logger.debug(mess);
            else if(level==1) m_Logger.info(mess);
            else if(level==-1) m_Logger.error(mess);
        }       
        protected void log(String message, Throwable exception) {
            m_Logger.error(message, exception);
        }       
        
        
        //线程池管理
    class MonitorRunnable implements Runnable 
    {
        ThreadPool p;
        Thread t;
        boolean shouldTerminate;
        long waitTimeout;
        MonitorRunnable(ThreadPool p) {
            shouldTerminate = false;
            this.p = p;
            waitTimeout = p.m_MonitorWaitTime;
            t = new Thread(this, p.getThreadPoolName()+"MonitorRunnable");
            t.start();
        }
        public void run() {
            while (true) {
                try {
                    synchronized (this) {
                        this.wait(waitTimeout);
                    }
                    if (shouldTerminate) {
                        break;
                    }
                    p.checkSpareControllers();
                } catch (Throwable t) {
                    t.printStackTrace();
                 p.log("ThreadPool MonitorRunnable Throwable: "+t.getMessage(), t);
                }
            }
        }
        
        public synchronized void terminate() {
            shouldTerminate = true;
            this.notify();
        }
    }
          //线程任务
        class ControlRunnable implements Runnable {
            ThreadPool m_ThreadPool;
            Thread t;
            ThreadRunnable toRun;
            boolean shouldTerminate;
            boolean shouldRun;
            long startTime;
            int m_ThreadNum;        ControlRunnable(ThreadPool pool, int threadNum) {
                toRun = null;
                shouldTerminate = false;
                shouldRun = false;
                this.m_ThreadNum = threadNum;
                this.m_ThreadPool = pool;
                t = new Thread(this, m_ThreadPool.getThreadPoolName()+"Thread["+m_ThreadNum+"]");
                t.setDaemon(true);
                t.start();
            }        public void run() {        
                while (true) {
                    try {
                        synchronized (this) {
                            if (!shouldRun && !shouldTerminate) {
                                this.wait();
                            }
                        }                    
                        if (shouldTerminate) break;
                        try {
                         startTime = System.currentTimeMillis();
                            if (shouldRun) {
                                toRun.runIt();
                                if (shouldTerminate) break;
                            }
                        } catch (Throwable t) {
                            t.printStackTrace();
                         m_ThreadPool.log("ThreadPool ControlRunnable Throwable:"+t.getMessage(), t);
                            //System.err.println("ControlRunnable Throwable: ");
                            //shouldTerminate = true;
                            //m_ThreadPool.notifyThreadEnd();
                        } finally{
                         try{
                         if(toRun!=null) toRun.terminate();
                         }catch(Exception e){
                         }
                         toRun=null;
                         shouldRun = false;
                         m_ThreadPool.log(0, "shouldRun="+shouldRun+", shouldTerminate="+shouldTerminate);
                        }
                        if (shouldTerminate) break;
                        m_ThreadPool.returnController(this);
                    } catch (InterruptedException ie) {
                    }
                }
            }        public synchronized void runIt(ThreadRunnable toRun) {
                if (toRun == null) {
                 m_ThreadPool.log(-1, "ThreadPool ControlRunnable runIt: No Runnable");
                    throw new NullPointerException("ThreadPool ControlRunnable runIt: No Runnable");
                }
                this.toRun = toRun;
                shouldRun = true;
                this.notify();
            }
            
            public String getThreadName(){
             return t.getName();
            }
            
            public int getThreadNum(){
             return m_ThreadNum;
            }
            
            public long getRunTime(){
             return (System.currentTimeMillis() - startTime);
            }        public void terminate() {
                shouldTerminate = true;
              if(toRun!=null) toRun.terminate();
              //m_ThreadPool.log(1, "ThreadPool "+t.getName()+" terminate");
                //this.notify();
                this.destroy();
            }
            void destroy(){
             try{
                t.join(10);
                if(t.isAlive()) t.interrupt();
                m_ThreadPool.log(1, "ThreadPool "+t.getName()+" destroy ");
             }catch(Exception e){
             m_ThreadPool.log(-1, "ThreadPool "+t.getName()+" destroy error: "+e.toString());
             }
            }
        }
        
    }