java如何监控一个方法的运行时间 [问题点数

在方法前定义 long time = System.currentTimeMillis();
 
方法执行中...

System.out.println(System.currentTimeMillis() - time);//此句是把方法的总执行时间打印在控制台

实现InvocationHandler,
开启线程调用你的这个方法,然后需要怎么控制都ok。 
这样也不用修改你原来的类。

InvocationHandler handler = new MyInvocationHandler(...);
     Class proxyClass = Proxy.getProxyClass(
         Foo.class.getClassLoader(), new Class[] { Foo.class });
     Foo f = (Foo) proxyClass.
         getConstructor(new Class[] { InvocationHandler.class }).
         newInstance(new Object[] { handler });

Foo.class就是你想要监听的原来那个类,
MyInvocationHandler就是你新写的类,其中需要实现
public Object invoke(Object proxy, Method method, Object[] args) throws
        Throwable {
    //这个就是你需要处理的地方
    if ("xxxx".equals(method.getName())) {
     Thread th = new Thread() {
             public void run() {
                 while(true) {
                    method.invoke(proxy, args);
            sleep(10000);//看你需要,再设置这个值
                       break; 
                 }
  ((xxx) proxy).releaseResource(); //到时间释放资源,不管前面method方法是否完成,比如关闭连接等
             }
         }
         th.start();
    }
    else {
       method.invoke(proxy, args);
    }
}

后来想着用两个线程序处理:
class myThread extends Thread{
public void run(){
int i=0;
while(true){
System.out.println("i="+i++);
try{
this.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
class DemonThread extends Thread{
private Thread tth;
private long rtime ;
public DemonThread(Thread thread,long time){
this.tth = thread;
this.rtime = time;
}
public void run(){
System.out.println("================= DemonThread start");
try{
this.tth.join(this.rtime);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("DemonThread wakeup");
        //this.tth.interrupt();
this.tth.stop();
        System.out.println("=================DemonThread  end ");
}
}
public class TestThread {
// 
public static void main(String[] args){
myThread myt = new myThread();
DemonThread demon = new DemonThread(myt,10000);
myt.start();
demon.start();
//myt.run();
}
}
试着用interrupt(),没有成功,只能用stop().但是这种过时的方法,API不推荐用,我也不清楚占用的资源有没有被成功的释放,
后来发现有个包apache.commons.httpclient里有个提供这种功能的方法 ,就去试了一下,结果成功了,呵呵,

下面说说我用的测试:

MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient();
HttpClientParams cparams = new HttpClientParams();
cparams.setSoTimeout(5000);//这里是设置要用的限制时间
client.setParams(cparams);
GetMethod method = new GetMethod(urlsource);//url地址,也就是你要处理的网络资源
method.setFollowRedirects(true);
try{int statusCode = client.executeMethod(method);
}
catch(Exception e){}
finally
{
//释放资源
 method.releaseConnection();
 manager.deleteClosedConnections();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章