任务类

Runnable

public interface Runnable {
    public abstract void run();
}

Runnable的代码非常简单,它是一个接口且只有一个run(),创建一个类实现它,把一些费时操作写在其中,然后使用某个线程去执行该Runnable实现类即可实现多线程。

Callable

public interface Callable<V> {
    V call() throws Exception;
}

Callable的代码也非常简单,不同的是它是一个泛型接口,call()函数返回的类型就是创建Callable传进来的V类型。 学习Callable对比着Runnable,这样就很快能理解它。Callable与Runnable的功能大致相似,Callable功能强大一些,就是被线程执行后,可以返回值,并且能抛出异常。

Future

public interface Future<V> {

    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();
    //阻塞,直到任务完成
    V get() throws InterruptedException, ExecutionException;
    //阻塞一段时间,或任务完成
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

Future是一个接口,定义了Future对于具体的Runnable或者Callable任务的执行结果进行取消、查询任务是否被取消,查询是否完成、获取结果。

Future例子
public class FutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<String> future = executorService.submit(new MyCallable());

        System.out.println("dosomething...");

        System.out.println("得到异步任务返回结果:" + future.get());
        System.out.println("Completed!");
        executorService.shutdown();
    }

    static class MyCallable implements Callable<String> {

        @Override
        public String call() throws Exception {
            System.out.println("做一些耗时的任务...");
            Thread.sleep(5000);
            return "OK";
        }
    }

}

Futrue可以监视目标线程调用call的情况,当你调用Future的get()方法以获得结果时,当前线程就开始阻塞,直接call方法结束返回结果。

FutureTask

FutureTask的父类是RunnableFuture,而RunnableFuture继承了Runnbale和Futrue这两个接口。

FutureTask例子
public class FutureTaskTest {

    public static void main(String[] args) {
        Callable<Integer> callable = new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        };
        FutureTask<Integer> future = new FutureTask<Integer>(callable);
        new Thread(future).start();
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

Last updated