Mark Knowledge of Java Thread (3): Future and Callable

My Future I Call the Shots

In sumary there are two ways to create a thread(new thread and implement runnable). Both of them are too simple to control its lifecycle and get result. Because the return type of run method is void. It should be improved. Luckily, we have future and callable implements to help us do that.

Future Is Not Always Good

People always have a perfect plan which is based on assumptive conditions. However the truth is not same. We expect a kind of power of control thus god give us future implement.

boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;     

En… frome these methods definition we can guess how they can be used. But we can get more information about its implementation class FutureTask

Give Me A Result

There is a big question is that thread can not return excution result. For this reason we can use Callable interface to finish this job with excute function.
Let’s see Callable interface first.

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Happy Coding Time

This is a easy to create new thread. This thread will caculates count from 1 to 100 and main thread will print its result.

Created with Raphaël 2.1.0 Main Thread Main Thread Caculator Caculator excute future task get result caculate count from 1 to 100 return result
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class Test {

    /**
     * Simple way to let t1 stop before t2
     * 
     * @param args
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("Start caculate.");
                int count = 0;
                for (int i = 1; i < 101; i++) {
                    count = count + i;
                }
                System.out.println("Finish caculate");
                return count;
            }
        });
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.submit(task);
        System.out.println("Result is:" + task.get());
        service.shutdown();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值