package threadPa;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author ltz:
* @version 上午11:43:37
* 类说明
*/
public class ThreadCallTest {
public static void main(String[]args){
ExecutorService exe=Executors.newCachedThreadPool();
Task task=new Task();
Future<Integer> result=exe.submit(task);
exe.shutdown();
try {
System.out.println("call result"+result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("over");
}
}
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("begin ....");
Thread.sleep(3000);
return 100;
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author ltz:
* @version 上午11:43:37
* 类说明
*/
public class ThreadCallTest {
public static void main(String[]args){
ExecutorService exe=Executors.newCachedThreadPool();
Task task=new Task();
Future<Integer> result=exe.submit(task);
exe.shutdown();
try {
System.out.println("call result"+result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("over");
}
}
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("begin ....");
Thread.sleep(3000);
return 100;
}
}
我们先来看一下FutureTask的实现:
1
|
public
class
FutureTask<V>
implements
RunnableFuture<V>
|
FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口的实现:
1
2
3
|
public
interface
RunnableFuture<V>
extends
Runnable, Future<V> {
void
run();
}
|
可以看出RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
FutureTask提供了2个构造器:
1
2
3
4
|
public
FutureTask(Callable<V> callable) {
}
public
FutureTask(Runnable runnable, V result) {
}
|
事实上,FutureTask是Future接口的一个唯一实现类。