Java Future 和 FutureTask 源码Demo
Future 是一个接口,看源码有Future 和 FutreTask 使用Demo
package java.util.concurrent; /**
* A <tt>Future</tt> represents the result of an asynchronous
* computation. Methods are provided to check if the computation is
* complete, to wait for its completion, and to retrieve the result of
* the computation. The result can only be retrieved using method
* <tt>get</tt> when the computation has completed, blocking if
* necessary until it is ready. Cancellation is performed by the
* <tt>cancel</tt> method. Additional methods are provided to
* determine if the task completed normally or was cancelled. Once a
* computation has completed, the computation cannot be cancelled.
* If you would like to use a <tt>Future</tt> for the sake
* of cancellability but not provide a usable result, you can
* declare types of the form {@code Future<?>} and
* return <tt>null</tt> as a result of the underlying task.
*
* <p>
* <b>Sample Usage</b> (Note that the following classes are all
* made-up.) <p>
* <pre> {@code
* interface ArchiveSearcher { String search(String target); }
* class App {
* ExecutorService executor = ...
* ArchiveSearcher searcher = ...
* void showSearch(final String target)
* throws InterruptedException {
* Future<String> future
* = executor.submit(new Callable<String>() {
* public String call() {
* return searcher.search(target);
* }});
* displayOtherThings(); // do other things while searching
* try {
* displayText(future.get()); // use future
* } catch (ExecutionException ex) { cleanup(); return; }
* }
* }}</pre>
*
* The {@link FutureTask} class is an implementation of <tt>Future</tt> that
* implements <tt>Runnable</tt>, and so may be executed by an <tt>Executor</tt>.
* For example, the above construction with <tt>submit</tt> could be replaced by:
* <pre> {@code
* FutureTask<String> future =
* new FutureTask<String>(new Callable<String>() {
* public String call() {
* return searcher.search(target);
* }});
* executor.execute(future);}</pre>
*
* <p>Memory consistency effects: Actions taken by the asynchronous computation
* <a href="package-summary.html#MemoryVisibility"> <i>happen-before</i></a>
* actions following the corresponding {@code Future.get()} in another thread.
*
* @see FutureTask
* @see Executor
* @since 1.5
* @author Doug Lea
* @param <V> The result type returned by this Future's <tt>get</tt> method
*/
public interface Future<V> {
1:测试类 App.
package com.future; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask; public class App {
static ExecutorService executor = null;
static ArchiveSearcher searcher = null; public static void main(String[] args) {
executor = Executors.newSingleThreadScheduledExecutor();
searcher = new ArchiveSearcherImp(); try {
showSearch("hello");
//showSearch2("world");
} catch (InterruptedException e) {
e.printStackTrace();
}
} static void showSearch(final String target) throws InterruptedException {
Future<String> future = executor.submit(new Callable<String>() {
public String call() {
return searcher.search(target);
}
});
System.out.println("displayOtherThings");
//boolean c = future.cancel(true);
// do other things while searching
try {
System.out.println("displayText(" + future.get() + ")");
} catch (Exception ex) {
System.out.println("Future Canceled:" + future.isCancelled());
return;
}
} static void showSearch2(final String target) throws InterruptedException {
FutureTask<String> future = new FutureTask<String>(
new Callable<String>() {
public String call() {
return searcher.search(target);
}
});
executor.execute(future);
} }
2:接口类
package com.future;
public interface ArchiveSearcher {
String search(String target);
}
3:接口实现类
package com.future;
public class ArchiveSearcherImp implements ArchiveSearcher {
public String search(String target) {
// TODO Auto-generated method stub
System.out.println("ArchiveSearcherImp:" + target);
return target + "End ";
}
}
这样小Demo就跑完了,帮助我们理解,
区别:(应用来自http://blog.csdn.net/naughty610/article/details/38961675)
Future是一个接口,代表可以取消的任务,并可以获得任务的执行结果
FutureTask 是基本的实现了Future和runnable接口
实现runnable接口,说明可以把FutureTask实例传入到Thread中,在一个新的线程中执行。
实现Future接口,说明可以从FutureTask中通过get取到任务的返回结果,也可以取消任务执行(通过interreput中断)

cancel方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false . 参数mayInterruptIfRunning 表示是否允许取消正在执行却没有执行完毕的任务,
如果设置true,则表示可以取消正在执行过程中的任务。
如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;
如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,
若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。
isDone

isDone方法表示任务是否已经完成,若任务完成,则返回true;
Java Future 和 FutureTask 源码Demo的更多相关文章
- Java多线程类FutureTask源码阅读以及浅析
FutureTask是一个具体的实现类,实现了RunnableFuture接口,RunnableFuture分别继承了Runnable和Future接口,因此FutureTask类既可以被线程执行,又 ...
- Java 多线程(五)—— 线程池基础 之 FutureTask源码解析
FutureTask是一个支持取消行为的异步任务执行器.该类实现了Future接口的方法. 如: 取消任务执行 查询任务是否执行完成 获取任务执行结果(”get“任务必须得执行完成才能获取结果,否则会 ...
- FutureTask源码深度剖析
FutureTask源码深度剖析 前言 在前面的文章自己动手写FutureTask当中我们已经仔细分析了FutureTask给我们提供的功能,并且深入分析了我们该如何实现它的功能,并且给出了使用Ree ...
- java 并发编程——Thread 源码重新学习
Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...
- 大文件拆分问题的java实践(附源码)
引子 大文件拆分问题涉及到io处理.并发编程.生产者/消费者模式的理解,是一个很好的综合应用场景,为此,花点时间做一些实践,对相关的知识做一次梳理和集成,总结一些共性的处理方案和思路,以供后续工作中借 ...
- java Thread 类的源码阅读(oracle jdk1.8)
java线程类的源码分析阅读技巧: 首先阅读thread类重点关注一下几个问题: 1.start() ,启动一个线程是如何实现的? 2.java线程状态机的变化过程以及如何实现的? 3. 1.star ...
- SwitchButton 开关按钮 的多种实现方式 (附源码DEMO)
http://blog.csdn.net/vipzjyno1/article/details/23707149 Switch开关android源码SwitchButton 刚开始接触开关样式的按钮是在 ...
- 大文件拆分方案的java实践(附源码)
引子 大文件拆分问题涉及到io处理.并发编程.生产者/消费者模式的理解,是一个很好的综合应用场景,为此,花点时间做一些实践,对相关的知识做一次梳理和集成,总结一些共性的处理方案和思路,以供后续工作中借 ...
- java多线程----线程池源码分析
http://www.cnblogs.com/skywang12345/p/3509954.html 线程池示例 在分析线程池之前,先看一个简单的线程池示例. 1 import java.util.c ...
随机推荐
- fl包下的TransitionManager的使用
http://www.republicofcode.com/tutorials/flash/as3transitionmanager/
- 00.嵌入式Linux开发环境搭建
3.虚拟机上网配置 虚拟机如果要从网上获取资源,就要能够访问外网.虚拟机有三种上网方式:桥接上网,NAT上网,单主机模式[没用过].本节从原理和操作2个方面讲了NAT方式和桥接方式这2种不同的虚拟机 ...
- vuex、redux、mobx 对比
出处:https://www.w3cplus.com/javascript/talk-about-front-end-state-management.html 其实大部分概念都差不多,只不过VUEX ...
- yii2 数据库查询
下面介绍一下 Yii2.0 对数据库 查询的一些简单的操作 User::find()->all(); 此方法返回所有数据: User::findOne($id); 此方法返回 主键 id=1 的 ...
- hdu 1506 Largest Rectangle in a Histogram——笛卡尔树
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1506 关于笛卡尔树的构建:https://www.cnblogs.com/reverymoon/p/952 ...
- 转 Fiddler导出jmeter脚本
前提条件: 1.下载安装抓包工具Fiddler 2.下载Fiddler插件,参考下载地址:http://download.csdn.net/ ...
- JSP中的MVC
如下图
- 深入理解ASP.NET MVC(目录)
学ASP.NET MVC2有一段时间了,也针对性的做了个练习.感觉这个框架还是不错的,所以决定要深入系统的学习一下.看到这样一本书: 作者博客:http://blog.stevensanderson. ...
- 【linux】Linux软连接和硬链接
1.Linux链接概念 Linux链接分两种,一种被称为硬链接(Hard Link),另一种被称为符号链接(Symbolic Link).默认情况下,ln命令产生硬链接. [硬连接] 硬连接指通过索引 ...
- 【jmeter】jmeter之“参数化”
参数化:简单的来理解一下,我们录制了一个脚本,这个脚本中有登录操作,需要输入用户名和密码,假如系统不允许相同的用户名和密码同时登录,或者想更好的模拟多个用户来登录系统. 这个时候就需要对用户名和密码进 ...