400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

java中Callable、FutureTask和Future接口的介绍

一. Callable接口与Runnable接口区别

创建java线程,我们经常使用两种方式:

创新互联建站是专业的胶州网站建设公司,胶州接单;提供成都网站设计、网站制作,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行胶州网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

但这两种方式有一个缺陷:在执行完任务之后无法直接获取执行结果。

1. 接口定义

1.1 Callable接口
public interface Callable {
    V call() throws Exception;
}
1.2 Runnable接口
public interface Runnable {
    public abstract void run();
}

2. 区别

二. Future接口和FutureTask实现类

1. Future接口定义了5个方法

public interface Future {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

2. FutureTask实现了RunnableFuture接口,RunnableFuture继承了Runnable接口和Future接口

public class FutureTask implements RunnableFuture
public interface RunnableFuture extends Runnable, Future {
    void run();
}

三. 基本用法举例

1. Runnable

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("线程执行中...");
    }
};
Thread thread = new Thread(runnable);
thread.start();

2. Callable

2.1 FutureTask
Callable < Integer > callable = new Callable < Integer > () {
    @Override
    public Integer call() throws Exception {
        System.out.println("线程执行中...");
        return 100;
    }
};
FutureTask < Integer > futureTask = new FutureTask < Integer > (callable);
new Thread(futureTask).start();
// 等待1秒,让线程执行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
    System.out.println("获取执行结果:" + futureTask.get());
}
2.2 Future
Callable < Integer > callable = new Callable < Integer > () {
    @Override
    public Integer call() throws Exception {
        System.out.println("线程执行中...");
        return 100;
    }
};
ExecutorService service = Executors.newCachedThreadPool();
Future < Integer > future = service.submit(callable);
// 等待1秒,让线程执行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
    System.out.println("获取执行结果:" + future.get());
}


名称栏目:java中Callable、FutureTask和Future接口的介绍
网页路径:http://mzwzsj.com/article/ijocoi.html

其他资讯

让你的专属顾问为你服务