Future 和 Callable 可以实现有返回结果的Runnable。
有三种状态:
- 等待运行(Waiting to run)
- 正在运行(Runnable)
- 运行完成(Completed)
可以同过Future.get() 获取结果,如果任务完成,立即返回,如果任务没有完成,将会等待任务完成后返回运行结果。
public class FutureDemo{
// 构造feture
privite final FutureTack<TestInfo> future = new FutureTask(new Callable<TestInfo>{
public Testinfo call() throws DataLoadExtion{
return loadDataInfo();
}
});
// 执行furute线程
private fianl Thread thread = new Thread(future);
// 封装线程启动
public void start(){
thread.start();
}
// 获取furute的返回结果 future.get();
public TestInfo get(){
try{
return feture.get()
}catch(Exception e){
throw e.getCause();
}
}
}