首先,定义Timable接口,接口中定义run()方法: package com.lulu.basic; public interface Timable { void run(); } 然后,写测量的时间的类:Timing package com.lulu.basic; import java.util.Calendar; public class Timing { public static void timing(Timable object){ long start = getCurrentMillionSecond(); object.run(); long end = getCurrentMillionSecond(); double timePassed = (end-start)/1000; System.out.println("执行用时共计" + timePassed +"秒!"); } private static long getCurrentMillionSecond(){ return Calendar.getInstance().getTimeInMillis(); } } 应用时,可根据具体的情况,要么让你的类实现Timable接口,要么把你的代码直接写到匿名类中即可: //仅举例匿名类的应用 public class Test{ public static void main(String[] args){ Timing.timing(new Timable(){ @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } }