深入Callable及Runnable两个接口 获取线程返回结果
今天碰到一个需要获取线程返回结果的业务场景,所以了解到了Callable接口。
先来看下下面这个例子:
public class ThreadTest { public static void main(String[] args) throws Exception {
ExecutorService exc = Executors.newCachedThreadPool();
try {
String result = null;
FutureTask<String> task = (FutureTask<String>) exc.submit(new Runnable() {
@Override
public void run() {
for (int i = 0; i <; i++) {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getClass() + "::线程执行中.." + i);
}
}
}, result); System.out.println("task return value:" + task.get()); FutureTask<String> callableTask = (FutureTask<String>) exc.submit(new Callable<String>() { @Override
public String call() throws InterruptedException {
for (int i = 0; i <; i++) {
Thread.sleep(100L);
System.out.println(this.getClass() + "::线程执行中.." + i);
}
return "success";
} }); System.out.println("提前出结果了 task return value:" + task.get()); System.out.println("callableTask return value:" + callableTask.get()); } finally {
exc.shutdown();
} } }
运行结果如下:
class thread.ThreadTest$1::线程执行中..0
class thread.ThreadTest$1::线程执行中..1
class thread.ThreadTest$1::线程执行中..2
class thread.ThreadTest$1::线程执行中..3
class thread.ThreadTest$1::线程执行中..4
class thread.ThreadTest$1::线程执行中..5
class thread.ThreadTest$1::线程执行中..6
class thread.ThreadTest$1::线程执行中..7
class thread.ThreadTest$1::线程执行中..8
class thread.ThreadTest$1::线程执行中..9
task return value:null
提前出结果了 task return value:null
class thread.ThreadTest$2::线程执行中..0
class thread.ThreadTest$2::线程执行中..1
class thread.ThreadTest$2::线程执行中..2
class thread.ThreadTest$2::线程执行中..3
class thread.ThreadTest$2::线程执行中..4
class thread.ThreadTest$2::线程执行中..5
class thread.ThreadTest$2::线程执行中..6
class thread.ThreadTest$2::线程执行中..7
class thread.ThreadTest$2::线程执行中..8
class thread.ThreadTest$2::线程执行中..9
callableTask return value:success
可以得到以下几点:
1 Runnable,Callable两个接口方法体不一样,前者为run,后者为call,且返回值也不一样;
2 Runnable接口由于run方法返回void所以无法解决线程成功后返回相应结果的问题;但是实现Callable接口的线程类可以,因为Callable的执行方法体call方法
可以返回对象。
3 由于runnable接口没有返回值,所以FutureTask为了解决此问题将runnable线程类通过支配器转换为callable线程。
4 当通过task对象调用get方法时,已经执行完成的现成可以立刻得到返回结果,但是还没执行完的线程一直在等待。
下面进入源码看看:
线程池执行submit方法时进入AbstractExecutorService类中的submit
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
这里好理解,将线程放入任务,由线程池的execute方法去执行。
执行完成后,当调用get方法时,会进入FutureTask的get方法:
public V get() throws InterruptedException, ExecutionException {
int s = state;
//当线程状态为新建活着执行中时一直调用awaitDone方法
if (s <= COMPLETING)
//循环判断线程状态是否已经执行成功,如果执行成功返回线程状态;其中还包括线程取消,中断等情况的判断。可参见下方源码。
//所以这里便是上面例子中为什么线程执行成功后即可立即得到结果,如果还没有执行成功
s = awaitDone(false, 0L);
//线程状态正常返回结果
return report(s);
}
awaitDone源码
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
} int s = state;
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
@SuppressWarnings("unchecked")
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
然后我们来看看FutureTask是如何对runnable线程进行转换的。代码也很简单:
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
深入Callable及Runnable两个接口 获取线程返回结果的更多相关文章
- python获取线程返回值
python获取线程返回值 前言 工作中的需求 将前端传过来的字符串信息通过算法转换成语音,并将语音文件返回回去 由于算法不是我写的,只需要调用即可,但是算法执行速度相当缓慢 我的优化思路是,将前端的 ...
- Callable 获取线程返回值
allable与 Future 两功能是Java在兴许版本号中为了适应多并法才增加的,Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它 ...
- android两种方式获取AsyncTask返回值
获取AsyncTask返回值,在Activity中使用. 引用链接:https://www.oschina.net/code/snippet_725438_49858#72630 [1].[代码] [ ...
- Android多线程的研究(8)——Java5于Futrue获取线程返回结果
我们先来看看ExecutorService操作的方法: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF3YW5nYW5iYW4=/font/5a6L5 ...
- Android多线程研究(8)——Java5中Futrue获取线程返回结果
我们先来看一下ExecutorService中的执行方法: 在上一篇中我们使用了execute方法启动线程池中的线程执行,这一篇我们来看看submit方法的使用:submit提交一个返回值的任务用于执 ...
- 异步模式模式Future(结合Callable可以获取线程返回结果)
submit 和 excute是有啥区别 如果有这样的需求: 多线程实现下载,提高效率. 不论是Thread类还是Runnable接口重写run方法,有个特点就是没有返回值~~~~~~ 我都主线程 如 ...
- Android(java)学习笔记66:实现Runnable接口创建线程 和 使用Callable和Future创建线程
1. 前面说的线程的实现是新写一个子类继承Thread: 是将类声明为 Thread 的子类.该子类应重写 Thread 类的 run 方法.接下来可以分配并启动该子类的实例 2. 这里说的方案2是指 ...
- Android(java)学习笔记6:实现Runnable接口创建线程 和 使用Callable和Future创建线程
1. 前面说的线程的实现是新写一个子类继承Thread: 是将类声明为 Thread 的子类.该子类应重写 Thread 类的 run 方法.接下来可以分配并启动该子类的实例 2. 这里说的方案2是指 ...
- 多线程----Thread类,Runnable接口,线程池,Callable接口,线程安全
1概念 1.1进程 进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并且具有一定独立功能. 任务管理器中: 1.2线程 线程是进程中的一个执行单元 ...
随机推荐
- 规范 : 过程 : login cookies sessionTimeOut
规范 用户登入网站将得到一个cookies,如果用户有2个account,各别登入admin page 和 client page,是会得到2个cookies. 在reload page时,后台会得到 ...
- spring mvc 结合 Hessian 配置
spring mvc 结合 Hessian 配置 1.先在web.xml中配置 <!-- Hessian配置 --> <servlet> <servlet-name> ...
- 关于margin
----W3School -----margin CSS 边距属性定义元素周围的空间.通过使用单独的属性,可以对上.右.下.左的外边距进行设置.也可以使用简写的外边距属性同时改变所有的外边距. 这个简 ...
- WEB标准了解
今天看到朋友的简历有一项“了解WEB标准”,就特地了解了一下什么是WEB标准.现在就一项一项地解开自己的疑惑. 1.什么是WEB标准 WEB标准大部分由万维网组织(W3C)制定的WEB程序开发规范.W ...
- SQL中with(nolock)作用说明
要提升SQL的查询效能,一般来说大家会以建立索引(index)为第一考虑.其实除了index的建立之外,当我们在下SQL Command时,在语法中加一段WITH (NOLOCK)可以改善在线大量查询 ...
- Junit使用教程
Junit是Java的单元测试工具,同时也是极限编程的好帮手.Junit4借助于Java5的Annotation(标注类)和静态导入的新特性,与Junit3有很大的区别,所以建议初学者直接使用Juni ...
- poj 2229 DP
Sumsets Time Limit: 2000MS Memory Limit: 200000K Total Submissions: 15326 Accepted: 6088 Descrip ...
- 3856: Monster
3856: Monster Time Limit: 1 Sec Memory Limit: 64 MBSubmit: 351 Solved: 161[Submit][Status][Discuss ...
- .Net程序员学用Oracle系列(21):分组查询(GROUP BY)
1.GROUP BY 标准分组 1.1.GROUP BY 概述 1.2.WHERE 和 HAVING 的区别? 2.GROUP BY 扩展分组 2.1.ROLLUP 分组 2.2.CUBE 分组 2. ...
- python list 切片实验
list[start:stop:step] >>> a_list=['hito','bb','cc','dd','ee','ff']>>> a_list[::-1] ...