/** * Created with IntelliJ IDEA. * User: 菜鳥大明 * Date: 14-10-23 * Time: 下午7:02 * To change this template use File | Settings | File Templates. */ public class MyCallable1 implements Callable { @Override public Object call() throws Exception { System.out.println("call"); return "end"; } public static void main(String[] args) throws ExecutionException, InterruptedException { MyCallable1 myCallable1 = new MyCallable1(); FutureTask fk = new MyFutureTask(myCallable1); // 它可以經過Thread包裝來直接運行, // Thread thread = new Thread(fk); // thread.start(); // 也可以提交給ExecuteService來運行, // ExecutorService exec = Executors.newCachedThreadPool(); // Future<String> future = exec.submit(myCallable1); // 並且還可以經過v get()返回運行結果, // 在線程體沒有運行完畢的時候,主線程一直堵塞等待,運行完則直接返回結果。 fk.run(); System.out.println(fk.get()); } } class MyFutureTask extends FutureTask { public MyFutureTask(Callable callable) { super(callable); } // 當線程運行結束,則運行done方法。@Override public void done() { // 此處通常用來計算任務運行耗時解析。html
System.out.println("done"); } }java