`
lj_1129
  • 浏览: 2280 次
文章分类
社区版块
存档分类
最新评论
阅读更多

 

import java.util.Random;

 

import org.junit.Test;

/**

 *

 * @author liangjun

 * @descriptionTODO  利用回调函数记录方法运行时间,处理异常等

 */

public class CallBackDemo {

   

    @Test

    public void testLog() {

        final CallBackDemo app = new CallBackDemo();

        LogUtil.getInstance().log(new CallBack() {

           publicvoid execute() throws InterruptedException {

              app.run();

           }

       });

    }

   

    protected void run() throws InterruptedException {

        Thread.sleep(new Random().nextInt(2000));

        System.out.println("I believe i can fly!");

        throw new RuntimeException("抛出运行时异常!");

    }

}

 

/**

 *

 * @author liangjun

 * @descriptionTODO回调函数接口

 */

interface CallBack {

    void execute() throws InterruptedException;

}

 

/**

 *

 * @author liangjun

 * @descriptionTODO 记录方法运行时间;处理异常;

 */

class LogUtil {

    private static LogUtil log;

    private LogUtil(){

    }

   

    public static LogUtil getInstance() {

       if(null == log) {

           synchronized (LogUtil.class) {

              if(null == log) {

                  log = new LogUtil();

              }

           }

       }

      

       returnlog;

    }

   

    publicvoid log (CallBack cb) {

       long start = System.currentTimeMillis();

       try {

           cb.execute();

       }catch(Exception e) {

           System.out.println(String.format("利用回调函数处理: %s", e.getMessage()));

       }

       long end = System.currentTimeMillis();

       System.out.println(String.format("%s 运行时间: %s ms!", cb.getClass().getName(),(end - start)));

    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics