demo
代码语言:javascript复制package jucTest;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class CallAbleReource implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("**进callable了 啦啦啦啦");
return 1024;
}
}
public class CallAble {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask= new FutureTask<Integer>(new CallAbleReource());
Thread thread=new Thread(futureTask,"FutureTask测试");
thread.start();
System.out.println("FutureTesk运行得到" futureTask.get());
}
}
描述 Callable接口本身不带有启动方法,我们需要利用FutureTesk
代码语言:javascript复制public class FutureTask<V> implements RunnableFuture<V>
FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口的实现
代码语言:javascript复制public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
可以看出RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
FutureTask提供了2个构造器:
代码语言:javascript复制public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}
事实上,FutureTask是Future接口的一个唯一实现类。