标签:style blog http color os java io strong ar
从java5开始,java提供了Callable接口,Callable接口提供了一个call方法可以作为线程的执行体,但call方法比run方法功能更加强大。主要体现在:示例代码:
Callable<Integer> c = new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("running..."); Thread.sleep(2000); return 215; } }; FutureTask<Integer> task = new FutureTask<>(c); new Thread(task).start(); try { System.out.println("result : "+task.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
public interface Callable<V> { V call() throws Exception; }
Runnable接口大家都很熟悉,那么这个Future接口提供了什么样的方法呢?
public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning);//取消Future里面关联的call方法 boolean isCancelled();//任务是否取消 boolean isDone();//任务是否完成 V get() throws InterruptedException, ExecutionException;//获取call方法的结果 V get(long timeout, TimeUnit unit)//设置超时时间,超过此时间未收到结果将抛出异常 throws InterruptedException, ExecutionException, TimeoutException; }
@Override public void run() { if (target != null) { target.run(); } }即判断是否传入了Runnable类型的target,如果有,将会执行Runnable的run方法,这里我们传入的是FutureTask,所以会调用FutureTask类的run方法:
public void run() { sync.innerRun(); }
void innerRun() { if (!compareAndSetState(READY, RUNNING)) return; runner = Thread.currentThread(); if (getState() == RUNNING) { // recheck after setting thread V result; try { result = callable.call();//调用的是callable的call方法 } catch (Throwable ex) { setException(ex); return; } set(result); } else { releaseShared(0); // cancel } }
public V get() throws InterruptedException, ExecutionException { return sync.innerGet(); }
V innerGet() throws InterruptedException, ExecutionException { acquireSharedInterruptibly(0); if (getState() == CANCELLED) throw new CancellationException(); if (exception != null) throw new ExecutionException(exception); return result; }返回了result变量。
标签:style blog http color os java io strong ar
原文地址:http://blog.csdn.net/chdjj/article/details/38900521