标签:
/** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object‘s * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
public interface Callable<V> {/** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
由代码可以清晰看出:两个接口的差别:Runnable只有一个run()函数,没有返回值;Callable一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。
使用实例:
Runnable():
class RunThread implements Runnable
{
@Override
public void run()
{
}
}
//调用
new thread(new RunThread()).start();
Callable<T>():
class CallThread implements Callable<String>
{
@Override
public String call() throws Exception {
return null;
}
}
//调用
ExecutorService pool = Executors.newCachedThreadPool();
Future<String> future = pool.submit(new CallThread());
String result = future.get();//注意这里要加上try_catch异常控制语句
pool.shutdown();
Future:
public interface Future<V> {/** * Attempts to cancel execution of this task. This attempt will */boolean cancel(boolean mayInterruptIfRunning); /** * Returns <tt>true</tt> if this task was cancelled before it complete */boolean isCancelled(); /** * Returns <tt>true</tt> if this task completed. */boolean isDone(); /** * Waits if necessary for the computation to complete, and then */ V get() throws InterruptedException, ExecutionException; /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result, if available. */ V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
Future表示异步计算的结果,它提供了检查计算是否完成的方法isDone(),以等待计算的完成,并检索计算的结果。Future的cancel()方法可以取消任务的执行,它有一布尔参数,参数为 true 表示立即中断任务的执行,参数为 false 表示允许正在运行的任务运行完成。Future的 get() 方法等待计算完成,获取计算结果;
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> {/** * Sets this Future to the result of its computation * unless it has been cancelled. */void run(); }
Runnable,Callable,Thread,Future,FutureTask关系
标签:
原文地址:http://blog.csdn.net/woliuyunyicai/article/details/45093321