Executor、Runable、Callable 和 Future 的基礎搭配

/**
 * 本篇主要目的爲測試 Executor 的 submit() 方法及返回的 Future 對象 <br />
 * 未包含 execute() 方法內容
 * 
 * @author Victor
 *
 */
public class FutureTest {

    private static ExecutorService threadpool = Executors.newSingleThreadExecutor();

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        // Runable + Future
        Future<?> runFuture = threadpool.submit(new RunnableThread());
        System.out.println(runFuture.get());

        // (Runnable -> Callable) + Future
        Future<?> runCallFuture1 = threadpool.submit(new RunnableThread(),
                new String("Runnable Finished : Translate by 'submit().'"));
        System.out.println(runCallFuture1.get());

        // (Runnable -> Callable) + Future
        Callable<String> runCall = Executors.callable(new RunnableThread(),
                "Runnable Finished : Translate by 'Executors.callable(...).");
        Future<String> runCallFuture2 = threadpool.submit(runCall);
        System.out.println(runCallFuture2.get());

        // Callable + Future
        Future<String> callFuture = threadpool.submit(new CallableThread());
        System.out.println(callFuture.get());

        // Callable + FutureTask
        FutureTask<String> futureTask = new FutureTask<>(new CallableThread());
        threadpool.submit(futureTask);
        System.out.println(futureTask.get());

        threadpool.shutdown();
    }
}

class RunnableThread implements Runnable {

    @Override
    public void run() {
        try {
            // 模擬耗時
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Runnable 執行完成 ");
    }

}

class CallableThread implements Callable<String> {

    @Override
    public String call() throws Exception {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Callable 執行完成 ");

        return "Callable Result : " + new Date().toString();
    }

}

運行結果

這裏寫圖片描述


備忘,歡迎交流。

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