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();
}

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