例示Executor + Callable + Future的使用

package player.kent.chen.learn.future;

import java.io.File;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;

public class HelloFuture {

    public static void main(String[] args) throws Throwable {

        //一个待完成事项
        Callable<String> task = new Callable<String>() {
            public String call() throws Exception {
                return FileUtils.readFileToString(new File("/home/kent/temp/1.txt"));
            }
        };

        //生成executor并异步执行
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(task);

        try {
            //阻塞式地等待结果
            String text = future.get();
            System.out.println(text);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            future.cancel(true); //既然都被打断了,future也可以取消了
        } catch (ExecutionException e) {
            throw e.getCause(); //task在执行时遇到的异常,比如FileNotFoundException
        } finally {
            //为了关闭线程池,这下面两句一般配合使用
            executor.shutdown();
            executor.awaitTermination(1000l, TimeUnit.SECONDS);
        }
    }

}


Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.