Callable,Future,FutureTask
public interface Callable<V>{
V call() throws Exception;
} public interface Runnable{
void run();
}
public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
//创建FutureTask对象,传入Callable对象;Callable对象,耗时操作是放在call方法里面的
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class FutureTaskExample { public static void main(String[] args) { Callable<String> worker = new Callable<String>() { @Override
public String call() throws Exception {
// TODO Auto-generated method stub
System.out.println("do computation");
return "computation result";
}
} ; FutureTask<String> future = new FutureTask<String>(worker) {
@Override
protected void done() { System.out.println("Done task");
}
}; new Thread(future) { @Override
public void run() {
future.run();
} }.start(); try {
System.out.println("computation:"+future.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
调用FutureTask的run方法就触发执行,可以查看FutureTask的源码得到解释:调用run,会导致调用sync.innerRun();而innerRun会调用传入的Callable对象的call方法:
public class FutureTask<V> implements RunnableFuture<V> { public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
sync = new Sync(callable);
} .....
// The following (duplicated) doc comment can be removed once
//
// 6270645: Javadoc comments should be inherited from most derived
// superinterface or superclass
// is fixed.
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
public void run() {
sync.innerRun();
} /**
* Synchronization control for FutureTask. Note that this must be
* a non-static inner class in order to invoke the protected
* <tt>done</tt> method. For clarity, all inner class support
* methods are same as outer, prefixed with "inner".
*
* Uses AQS sync state to represent run status
*/
private final class Sync extends AbstractQueuedSynchronizer { void innerRun() {
if (!compareAndSetState(READY, RUNNING))
return; runner = Thread.currentThread();
if (getState() == RUNNING) { // recheck after setting thread
V result;
try {
result = callable.call();
} catch (Throwable ex) {
setException(ex);
return;
}
set(result);
} else {
releaseShared(0); // cancel
}
} } }
2.实现例子
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class FutureTaskExample { public static void main(String[] args) { Callable<String> worker = new Callable<String>() { @Override
public String call() throws Exception {
// TODO Auto-generated method stub
System.out.println("do computation");
return "computation result";
}
} ; FutureTask<String> future = new FutureTask<String>(worker) {
@Override
protected void done() { System.out.println("Done task");
}
}; new Thread(future) { @Override
public void run() {
future.run();
} }.start(); try {
System.out.println("computation:"+future.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.总结
Callable,Future,FutureTask的更多相关文章
- Java 并发编程——Callable+Future+FutureTask
Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...
- 12 Callable & Future & FutureTask
创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果. 如果需要获取执行结果,就必须通过共享变量或者使用 ...
- java 并发runable,callable,future,futureTask
转载自:http://www.cnblogs.com/dolphin0520/p/3949310.html package future_call; import java.util.concurre ...
- Java多线程:Callable,Future,FutureTask
一.Future Future和Callable基本是成对出现的,Callable负责产生结果,Future负责获取结果. 1.Callable接口类似于Runnable,只是Runnable ...
- java callable future futuretask
Runnbale封装一个异步运行的任务,可以把它想象成一个没有任何参数和返回值的异步方法.Callable和Runnable相似,但是它有返回值.Callable接口是参数化的类型,只有一个方法cal ...
- Callable, Runnable, Future, FutureTask
Java并发编程之Callable, Runnable, Future, FutureTask Java中存在Callable, Runnable, Future, FutureTask这几个与线程相 ...
- Future、Callable 、FutureTask详解
1.Future和Callable Future是一个接口表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果.Future提供了get().cancel().isC ...
- Java并发编程:ThreadPoolExecutor + Callable + Future(FutureTask) 探知线程的执行状况
如题 (总结要点) 使用ThreadPoolExecutor来创建线程,使用Callable + Future 来执行并探知线程执行情况: V get (long timeout, TimeUnit ...
- paip.java 多线程参数以及返回值Future FutureTask 的使用.
paip.java 多线程参数以及返回值Future FutureTask 的使用. 在并发编程时,一般使用runnable,然后扔给线程池完事,这种情况下不需要线程的结果. 所以run的返回值是vo ...
随机推荐
- Android之自定义View学习(一)
Android之自定义View学习(一) Canvas常用方法: 图片来源 /** * Created by SiberiaDante on 2017/6/3. */ public class Bas ...
- Beta阶段——3
一.提供当天站立式会议照片一张: 二. 每个人的工作 (有work item 的ID) (1) 昨天已完成的工作: 今天主要是对管理员功能进行改进,解决了Alpha阶段出现的一些问题 (2) 今天计划 ...
- SEO优化之HTML代码优化最重要的5个标签
众所周知,HTML代码一直是搜索引擎抓取的重点.搜索引擎会将HTML中的某些元素标签作为影响网页排名的重要依据 在我们之前的文章中也或多或少地向大家介绍了有关HTML代码的优化技巧,接下来将系统地讲解 ...
- strtr、str_replace()、substr_replace、preg_replace之间的区别
strtr(string, from, to): 逐个字符开始替换,以from跟to中长度较较短的一个为准,例如: strtr("aidengni","ai", ...
- MicrosoftFixit50688 [Windows7事件ID10,WMI错误的解决方法
Windows7事件记录中有如下错误提示: "Event filter with query "SELECT * FROM __InstanceModificationEve ...
- 开发者应该掌握的Java代码优化技能
就像鲸鱼吃虾米一样,也许吃一个两个虾米对于鲸鱼来说作用不大,但是吃的虾米多了,鲸鱼自然饱了. 代码优化一样,也许一个两个的优化,对于提升代码的运行效率意义不大,但是只要处处都能注意代码优化,总体来说对 ...
- Java 继承和多态
Java 继承和多态 Java 继承 继承的概念 继承是java面向对象编程技术的一块基石,因 ...
- BZOJ3252 攻略(贪心+dfs序+线段树)
考虑贪心,每次选价值最大的链.选完之后对于链上点dfs序暴力修改子树.因为每个点最多被选一次,复杂度非常正确. #include<iostream> #include<cstdio& ...
- bootstrap栅格系统错位问题
在项目中div可以设置属性class=“col-size-x” //size取值为xs,sm,md,lg:x取值为1-12 可以让此div占据本行的 x/12 .col-xs- 超小屏幕 手机 (&l ...
- 数据挖掘领域经典分类算法 —— C4.5算法(附python实现代码)
目录 理论介绍 什么是分类 分类的步骤 什么是决策树 决策树归纳 信息增益 相关理论基础 计算公式 ID3 C4.5 python实现 参考资料 理论介绍 什么是分类 分类属于机器学习中监督学习的一种 ...