当前位置: 首页 > news >正文

FutureTask

1. 作用

  • 异步操作
  • 获取执行结果
  • 取消任务执行,判断是否取消执行
  • 判断任务执行是否完毕

2. demo

public static void main(String[] args) throws Exception {Callable<String> callable= () -> search();FutureTask<String> futureTask=new FutureTask<>(callable);futureTask.run();// 持续阻塞String s = futureTask.get();System.out.println(s);System.out.println("主线程收集了1颗龙珠");}/*** 收集龙珠*/public static String search() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}return "找到了1颗龙珠";}

3. 原理

3.1 类关系图

3.2 主要流程

3.3 方法

3.3.1 futureTask.run()

    public void run() {if (state != NEW ||!UNSAFE.compareAndSwapObject(this, runnerOffset,null, Thread.currentThread()))return;try {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);}if (ran)// 将结果赋值给outcomeset(result);}} finally {runner = null;int s = state;if (s >= INTERRUPTING)handlePossibleCancellationInterrupt(s);}}protected void set(V v) {if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {outcome = v;UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final statefinishCompletion();}}

3.3.2 futureTask.get()

    public V get() throws InterruptedException, ExecutionException {// 当前状态未完成时,进入自旋等待int s = state;if (s <= COMPLETING)s = awaitDone(false, 0L);// 返回子进程的执行结果return report(s);}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 yetThread.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;}// 多次等待后park一会(自己会醒)LockSupport.parkNanos(this, nanos);}else// 多次等待后park一会(自己不会醒)LockSupport.park(this);}}// 获取结果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);}

http://www.lryc.cn/news/252838.html

相关文章:

  • 【力扣热题100】207. 课程表 python 拓扑排序
  • 【滑动窗口】LeetCode2953:统计完全子字符串
  • base64转PDF
  • clip-path,css裁剪函数
  • 第二证券:食品饮料板块拉升,乳业股亮眼,西部牧业“20cm”涨停
  • React 好用的工具库
  • C++面试宝典第2题:逆序输出整数
  • Twincat功能块使用经验总结
  • 香港服务器时间不准,差8小时
  • C++ 抽象类和接口 详解
  • 【Linux】awk 使用
  • LeetCode力扣每日一题(Java):9、回文数
  • WPF前端实现人脸扫描动画效果
  • 更改AndroidStudio模拟器位置
  • Dash 协议介绍
  • RabbitMQ的消息发送和接收机制
  • 记录111
  • 振动和震动的区别?
  • 3DMM模型
  • Python 3 使用 write()、writelines() 函数写入文件
  • 鸿蒙(HarmonyOS)应用开发——管理组件状态
  • 倚天屠龙:Github Copilot vs Cursor
  • 【web安全】RCE漏洞原理
  • EI论文复现:基于组合双向拍卖的共享储能机制研究程序代码!
  • ThinkPHP 5 中,你可以使用定时任务调度器(TaskScheduler)来执行其他定时任务
  • mysql:免费的GUI客户端工具推荐并介绍常用的操作
  • [Unity数据管理]自定义菜单创建Unity内部数据表(ScriptableObject)
  • 使用JAVA语言写一个排队叫号的小程序
  • openGauss学习笔记-140 openGauss 数据库运维-例行维护-例行维护表
  • ubuntu20.04使用LIO-SAM对热室空间进行重建