Callable的基本使用和源码解读
1 使用#
java.util.concurrent.Callable
是有返回值的多线程任务:
public interface Callable<V> {
V call() throws Exception;
}
通过实现Callable
接口,在call()
方法中定义业务逻辑,并返回处理结果。例如:
Callable<Integer> task = new Callable() {
@Override
public Integer call() throws Exception {
// 业务处理
return 100;
}
};
在Java中,启动线程的唯一方式是Thread
类,它可以将Runnable
对象作为线程执行的任务。但是,我们发现Callable跟Runnable并没有关系。
为了执行Callable任务,我们需要使用FutureTask
作为适配器,将任务包装起来。
FutureTask是Runnable的实现类,其中定义了执行Callable任务的模板方法。
当任务执行完成之后,可以使用FutureTask#get()方法获取处理结果。
因此,我们使用以下方式执行Callable任务:
FutureTask futureTask = new FutureTask(task);
Thread thread = new Thread(futureTask);
thread.start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
2 源码#
在创建FutureTask
对象时,会保存callable
任务:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
FutureTask实现了Runnable接口,在线程运行时,会执行其run()
方法:
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
// 执行callable任务
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
// 将处理结果设置到成员变量outcome
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
通过java.util.concurrent.FutureTask#get()
方法,可以获取到执行结果:
public V get() throws InterruptedException, ExecutionException {
int s = state;
// 如果任务未完成,等待任务完成
if (s <= COMPLETING)
s = awaitDone(false, 0L);
// 返回处理结果:outcome
return report(s);
}
java.util.concurrent.FutureTask#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;
}
// 如果任务执行马上完成,让出CPU
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);
}
}
分类:
Java / 多线程
, Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了