求助 如何监测java某个线程内存的占用情况啊?

jlsf_zym 2010-10-18 08:45:23
求助 如何监测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
...全文
577 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
myisfei 2010-10-18
  • 打赏
  • 举报
回复
我们公司的多程序都是用这管理的,当然这只是一个通用的核心管理部分,怎么样用看你水平,但也包括了多线程控制的主要方法了
myisfei 2010-10-18
  • 打赏
  • 举报
回复
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());
}
}
}

}
myisfei 2010-10-18
  • 打赏
  • 举报
回复
以下是一个完整的程序
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);
}
}
请先阅读帮助文档:http://ismyway.com/help [2009.1.1] Ver 3.2.26 ※如果安装提示证书过期或无法安装,请在手机上将时间改为2008.8.8,安装设置完成后再将日期改回即可!※ 增加天语的按键映射 增加三星的背景灯控制功能(该功能未在真机上测试过) 删除图片浏览中的部分功能,由于这部分功能需要较大的内存,导致在大部分手机上无法完成,同时也引起背景图片无法设置成功 触摸屏用户可以不再受滚动条限制,在屏幕上任意地方都可以进行拖动 选择键盘映射为其它时无法再次更改的BUG 用户输入的颜色值无法保存的BUG 修正英文单词分词时会多添加一个空行的BUG 繁体语言措词上的修正 阅读设置中增加一个“文件缓存”选项,默认情况下是开启的,在NOKIA手机上会提高UMD等文件的表现,但由于测试并不充足,如果程序经常在阅读时出错,请关闭该选项(其它手机是否开启该选项并无明显的影响) 修正编辑文件后无法保存的BUG [2008.10.27] Ver 3.2.24 ※如果安装提示证书过期或无法安装,请在手机上将时间改为2008.8.8,安装设置完成后再将日期改回即可!※ 改进的颜色选择方式 允许用户重新选择键盘映射 HTML阅读时的错误 进一步完善编辑功能(仍有少许BUG,请继续反馈,谢谢) 新建文件后自动跳转到编辑中 改进的文件操作方式,速度轻微提升 UMD速度明显提升,并且减少内存占用,特别是在NOKIA手机上,表现提升超过600% 改进的输入框模式,以使得能适应更多的手机如天语等 [2008.10.21] Ver 3.2.23 为了提高运行效率,以下功能在LITE上将被取消(自定义欢迎页问候语;欢迎页背景图) 取消了JAR的支持,提高运行效率 修正打开大ZIP文件时的内存溢出错误 ·修正:  自动滚屏到末尾时,滚屏功能将停止 [2008.10.4] Ver 3.2.22 暂时删除了播放功能及网络相关的功能,由于以上两项功能一直没有能稳定下来,故暂时删除 增强了ZIP功能,支持带文件夹结构的ZIP/JAR文件 (对于大部分JAR电子书都,可以从文件管理器中找到非.class结尾的文件,并且选择打开为UNICODE/TXT阅读) (对于NOKIA手机及其它部分手机,由于安全策略的限制,在Anyview的文件管理器中无法查看后缀为.jar的文件) 自定义问候语(系统路径下dictum.rc文件,格式参见jar包中的dictum.rc文件,保存时使用UTF-8编码,可写条目为0~9/a~z/A~Z,置空时表示不显示问候语) ·修正:  0键在各偏好中切换时亮度混乱的问题  部分手机上无法新建文件夹 [2008.9.11] Ver 3.2.21 修正动画参数无法保存的BUG 动画效果不再对阅读翻页有作用 [2008.8.29] Ver 3.2.21 可将正在阅读的内容通过短信与好友分享 增加一种新的滚屏方式:波浪,同时,阅读时3键不再使用默认的像素滚屏,而会使用最后一次使用的滚屏方式 任何可用的外置字库都可以作为内置字库存在,在jar包中存在dot.font会被当为内置字库加载 加快大文件的打开速度,特别是对于NOKIA手机,S60上,打开20M文件,97%左右的位置不超过15秒 允许用户打开动画效果 ·M600/P990/P1/W950  修正键盘映射时“内存不足”的BUG ·E680/A780  选中后台播放后无法启动的BUG [2008.7.30] Ver 3.2.20 调整部分索爱手机上背景灯控制的逻辑 修正看图片时按0键出错的BUG 旋转屏幕引起的字外出 打开LRC最后出错 阅读到尾部弹出“上一个/下一个”窗口中的文件名过长不刷新的问题 偏好切换时亮度混乱的问题 在NOKIA上,当系统路径设置为根目录是无法启动的BUG E398上可以开关键盘灯 UIQ系统在退出时可以保持亮度 索爱上按“返回”键后导致阅读出现白屏的BUG 阅读时切换屏幕方向导致字体超出屏幕的BUG 欢迎屏幕上的日期使用中文显示 如果使用触屏手机,跳转改为进度条模式,以方便触屏操作 系统路径下如果存在bg.png文件,则会作为欢迎界面的背景图片显示(右下角) 减少跳转及翻页中出现乱码的机率 提高阅读时绘图效率,滚屏效率同样提高 播放时,暂停会导致声音爆至最大的BUG 内置“忘记月亮”制作的两款主题《典雅红》《黑橙》,并且更换主题不再要求退出 文件管理器中支持“剪切”功能 文件管理器中新增转换UMD为TXT的功能(解开操作,解开2无效!) 增加了编辑功能(尽管没有限制文件大小,但请别编辑过大的文件,另外,为了提高速度,不进行全文排版,有时候表现可能会有些不习惯),以后会进一步完善 启动时,会自动识别NOKIA、SONYER

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧