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();
    }

}

运行结果

这里写图片描述


备忘,欢迎交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值