Future接口介绍:
在Java中,如果需要设定代码执行的最长时间,即超时,可以用Java线程池ExecutorService类配合Future接口来实现。 Future接口是Java标准API的一部分,在java.util.concurrent包中。Future接口是Java线程Future模式的实现,可以来进行异步计算。
Future模式可以这样来描述:我有一个任务,提交给了Future,Future替我完成这个任务。期间我自己可以去做任何想做的事情。一段时间之后,我就便可以从Future那儿取出结果。就相当于下了一张订货单,一段时间后可以拿着提订单来提货,这期间可以干别的任何事情。其中Future 接口就是订货单,真正处理订单的是Executor类,它根据Future接口的要求来生产产品。
Future接口提供方法来检测任务是否被执行完,等待任务执行完获得结果,也可以设置任务执行的超时时间。这个设置超时的方法就是实现Java程序执行超时的关键。
Future接口是一个泛型接口,严格的格式应该是Future<V>,其中V代表了Future执行的任务返回值的类型。 Future接口的方法介绍如下:
- boolean cancel (boolean mayInterruptIfRunning) 取消任务的执行。参数指定是否立即中断任务执行,或者等等任务结束
- boolean isCancelled () 任务是否已经取消,任务正常完成前将其取消,则返回 true
- boolean isDone () 任务是否已经完成。需要注意的是如果任务正常终止、异常或取消,都将返回true
- V get () throws InterruptedException, ExecutionException 等待任务执行结束,然后获得V类型的结果。InterruptedException 线程被中断异常, ExecutionException任务执行异常,如果任务被取消,还会抛出
CancellationException
- V get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 同上面的get功能一样,多了设置超时时间。参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计算超时,将抛出TimeoutException
Future的实现类有java.util.concurrent.FutureTask<V>即 javax.swing.SwingWorker<T,V>。通常使用FutureTask来处理我们的任务。FutureTask类同时又实现了Runnable接口,所以可以直接提交给Executor执行。使用FutureTask实现超时执行的代码如下:
<span style="font-size:18px;">ExecutorService executor = Executors.newSingleThreadExecutor();不直接构造Future对象,也可以使用ExecutorService.submit方法来获得Future对象,submit方法即支持以 Callable接口类型,也支持Runnable接口作为参数,具有很大的灵活性。使用示例如下:
FutureTask<String> future =
new FutureTask<String>(new Callable<String>() {//使用Callable接口作为构造参数
public String call() {
//真正的任务在这里执行,这里的返回值类型为String,可以为任意类型
}});
executor.execute(future);
//在这里可以做别的任何事情
try {
result = future.get(5000, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒。同样可以用future.get(),不设置执行超时时间取得结果
} catch (InterruptedException e) {
futureTask.cancel(true);
} catch (ExecutionException e) {
futureTask.cancel(true);
} catch (TimeoutException e) {
futureTask.cancel(true);
} finally {
executor.shutdown();
}</span>
<span style="font-size:18px;">ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask<String> future = executor.submit(
new Callable<String>() {//使用Callable接口作为构造参数
public String call() {
//真正的任务在这里执行,这里的返回值类型为String,可以为任意类型
}});
//在这里可以做别的任何事情
//同上面取得结果的代码</span>
Future模式:
什么是future:future的原理是当你申请资源(计算资源或I/O资源)时,立即返回一个虚拟的资源句柄,当真正使用的时候,再将虚拟的句柄转化成真正的资源,相当于预获取。
Future使用方法伪代码如下:
Future::Future(Job_func):
Thread.run(Job_func);
end
Future::get_result():
While(result == NULL):
Thread.sleep()
Return result
End
uture模式只有在并行运算的框架内才有意义。当一个逻辑操作设计的耗时操作比较多时,可以将耗时操作拆分成多个不太耗时的子操作,使子操作并行的执行,逻辑层依次获取子操作的结果。架设我们要执行一个逻辑操作,要求执行一次mysql查询,还要读一次文件,如果使用普通的同步方式:
Do:
query = Mysql_query()
file = File_read()
Do_thing(query, file)
Done
使用future模式示例如下:
Do:
Future a(Mysql_query)//! 非阻塞
Future b(File_read) //! 非阻塞
Query = a.get_result() //! 阻塞获取结果
File = b.get_result() //! 阻塞获取结果
Do_thing(query, file)
Done
这样sql查询和读取文件实现了并行运行,同步等待的时间为二者开销较大的运行时间。
适于使用future模式的时机:在客户端,我们常常需要阻塞的获取结果,通过future模式可以大大提高响应速度。而在服务端程序,阻塞操作会降低系统的吞吐量,future模式试用的范围较窄,一般服务端采用异步回调的方式,将耗时的操作并行化,再通过回调方式将结果合并。Future构造时生成了虚拟的结果,如果使用这个结果越晚,当get_result时越不容易阻塞,所以从生成future到获取结果的间隔越长,future模式的功效越大。
android中SafeAsyncTask异步操作类中使用:
/**
* 使用JUC实现的异步任务处理类,该类实现异步任务处理外,还另外定义线程中断和捕捉异常声明周期方法
* 使用限制: 不能处理任务进度
*
* @param <ResultT>
*/
public abstract class SafeAsyncTask<ResultT> implements Callable<ResultT> {
public static final int DEFAULT_POOL_SIZE = Runtime.getRuntime().availableProcessors() << 1;
protected static final Executor DEFAULT_EXECUTOR = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
protected Handler handler;
protected Executor executor;
protected StackTraceElement[] launchLocation;
protected FutureTask<Void> future;
/**
* Sets executor to Executors.newFixedThreadPool(DEFAULT_POOL_SIZE) and
* Handler to new Handler()
*/
public SafeAsyncTask() {
this.executor = DEFAULT_EXECUTOR;
}
/**
* Sets executor to Executors.newFixedThreadPool(DEFAULT_POOL_SIZE)
*/
public SafeAsyncTask( Handler handler ) {
this.handler = handler;
this.executor = DEFAULT_EXECUTOR;
}
/**
* Sets Handler to new Handler()
*/
public SafeAsyncTask( Executor executor ) {
this.executor = executor;
}
public SafeAsyncTask( Handler handler, Executor executor ) {
this.handler = handler;
this.executor = executor;
}
public FutureTask<Void> future() {
future = new FutureTask<Void>( newTask() );
return future;
}
public SafeAsyncTask<ResultT> executor( Executor executor ) {
this.executor = executor;
return this;
}
public Executor executor() {
return executor;
}
public SafeAsyncTask<ResultT> handler( Handler handler ) {
this.handler = handler;
return this;
}
public Handler handler() {
return handler;
}
public void execute() {
execute(Thread.currentThread().getStackTrace());
}
protected void execute( StackTraceElement[] launchLocation ) {
this.launchLocation = launchLocation;
executor.execute( future() );
}
public boolean cancel( boolean mayInterruptIfRunning ) {
if( future==null )
throw new UnsupportedOperationException("You cannot cancel this task before calling future()");
return future.cancel(mayInterruptIfRunning);
}
/**
* @throws Exception, captured on passed to onException() if present.
*/
protected void onPreExecute() throws Exception {}
/**
* @param t the result of {@link #call()}
* @throws Exception, captured on passed to onException() if present.
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onSuccess( ResultT t ) throws Exception {}
/**
* Called when the thread has been interrupted, likely because
* the task was canceled.
*
* By default, calls {@link #onException(Exception)}, but this method
* may be overridden to handle interruptions differently than other
* exceptions.
*
* @param e an InterruptedException or InterruptedIOException
*/
protected void onInterrupted( Exception e ) {
onException(e);
}
/**
* Logs the exception as an Error by default, but this method may
* be overridden by subclasses.
*
* @param e the exception thrown from {@link #onPreExecute()}, {@link #call()}, or {@link #onSuccess(Object)}
* @throws RuntimeException, ignored
*/
protected void onException( Exception e ) throws RuntimeException {
onThrowable(e);
}
protected void onThrowable( Throwable t ) throws RuntimeException {
Ln.e(t, "Throwable caught during background processing");
}
/**
* @throws RuntimeException, ignored
*/
protected void onFinally() throws RuntimeException {}
protected Task<ResultT> newTask() {
return new Task<ResultT>(this);
}
public static class Task<ResultT> implements Callable<Void> {
protected SafeAsyncTask<ResultT> parent;
protected Handler handler;
public Task(SafeAsyncTask<ResultT> parent) {
this.parent = parent;
this.handler = parent.handler!=null ? parent.handler : new Handler(Looper.getMainLooper());
}
public Void call() throws Exception {
try {
doPreExecute();
doSuccess(doCall());
} catch( final Exception e ) {
try {
doException(e);
} catch( Exception f ) {
// logged but ignored
Ln.e(f);
}
} catch( final Throwable t ) {
try {
doThrowable(t);
} catch( Exception f ) {
// logged but ignored
Ln.e(f);
}
} finally {
doFinally();
}
return null;
}
protected void doPreExecute() throws Exception {
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
parent.onPreExecute();
return null;
}
});
}
protected ResultT doCall() throws Exception {
return parent.call();
}
protected void doSuccess( final ResultT r ) throws Exception {
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
parent.onSuccess(r);
return null;
}
});
}
protected void doException( final Exception e ) throws Exception {
if( parent.launchLocation!=null ) {
final ArrayList<StackTraceElement> stack = new ArrayList<StackTraceElement>(Arrays.asList(e.getStackTrace()));
stack.addAll(Arrays.asList(parent.launchLocation));
e.setStackTrace(stack.toArray(new StackTraceElement[stack.size()]));
}
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
if( e instanceof InterruptedException || e instanceof InterruptedIOException )
parent.onInterrupted(e);
else
parent.onException(e);
return null;
}
});
}
protected void doThrowable( final Throwable e ) throws Exception {
if( parent.launchLocation!=null ) {
final ArrayList<StackTraceElement> stack = new ArrayList<StackTraceElement>(Arrays.asList(e.getStackTrace()));
stack.addAll(Arrays.asList(parent.launchLocation));
e.setStackTrace(stack.toArray(new StackTraceElement[stack.size()]));
}
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
parent.onThrowable(e);
return null;
}
});
}
protected void doFinally() throws Exception {
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
parent.onFinally();
return null;
}
});
}
/**
* Posts the specified runnable to the UI thread using a handler,
* and waits for operation to finish. If there's an exception,
* it captures it and rethrows it.
* @param c the callable to post
* @throws Exception on error
*/
protected void postToUiThreadAndWait( final Callable c ) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final Exception[] exceptions = new Exception[1];
// Execute onSuccess in the UI thread, but wait
// for it to complete.
// If it throws an exception, capture that exception
// and rethrow it later.
handler.post( new Runnable() {
public void run() {
try {
c.call();
} catch( Exception e ) {
exceptions[0] = e;
} finally {
latch.countDown();
}
}
});
// Wait for onSuccess to finish
latch.await();
if( exceptions[0] != null )
throw exceptions[0];
}
}
}
引用: http://westyi.iteye.com/blog/714935#
http://blog.chinaunix.net/uid-23093301-id-190969.html