Future小例子

Flutter-事件机制---Future-和-MicroTask-全解析,腾讯Android面试题 Dart 中事件机制的实现 :Main isolate 中有一个Looper,但存在两个Queue:Event Queue 和 Microtask Queue 。 因为 isolate 是单线程实体,所以 isolate中的代码是按顺序执行的。 所以 dart 中的代码执行优先级可以分为三个级别: 在 Main 中写代码将最先执行; 执行完 Main 中的代码,然后会检查并执行 Microtask Queue 中的任务, 通常使用 scheduleMicrotask 将事件添加到 MicroTask Qu 阅读详情

一、Future的应用 

void eventLoopDemo() {
  print('eventLoopDemo #1 of 2');
  Future.microtask(() => print('microtask #1 of 3'));
  //使用delay方式,是将此task放到queue的尾部,
  //若前面有耗时操作,不一定能准时执行
  new Future.delayed(
      new Duration(seconds: 1), () => print('event #1 (delayed)'));
  //使用then,是表示在此task执行后立刻执行
  new Future(() => print('event #2 of 4'))
      .then((_) => print('event #2a'))
      .then((_) {
    print('event #2b');
    Future.microtask(() => print('microtask #0 (from event #2b)'));
  }).then((_) => print('event #2c'));

  Future.microtask(() => print('microtask #2 of 3'));

  new Future(() => print('event #3 of 4'))
      .then((_) => new Future(() => print('event #3a (a new event)')))
      .then((_) => print('event #3b'));

  new Future(() => print('event #4 of 4')).then((_) {
    new Future(() => print('event #4a'));
  }).then((_) => print('event #4b'));

  Future.microtask(() => print('microtask #3 of 3'));
  print('eventLoopDemo #2 of 2');
}

//打印结果
isolateDemo #1 of 2
isolateDemo #2 of 2
microtask #1 of 3
microtask #2 of 3
microtask #3 of 3
event #2 of 4
event #2a
event #2b
event #2c
microtask #0 (from event #2b)
event #3 of 4
event #4 of 4
event #4b
event #3a (a new event)
event #3b
event #4a
event #1 (delayed)

其中拆解Future

void eventLoopDemo() {
  //使用delay方式,是将此task放到queue的尾部,
  //若前面有耗时操作,不一定能准时执行

  new Future(() => print('cxb #3 of 4'))
      .then((_) => new Future(() => print('cxb #3a (a new cxb)')))
      .then((_) => print('cxb #3b'));

  new Future(() => print('cxb #4 of 4')).then((_) {
    new Future(() => print('cxb #4a'));
  }).then((_) => print('cxb #4b'));
}

打印:
flutter: cxb #3 of 4
flutter: cxb #4 of 4
flutter: cxb #4b
flutter: cxb #3a (a new cxb)
flutter: cxb #3b
flutter: cxb #4a

如果把  cxb #4a 这一行换成

void eventLoopDemo() {
  //使用delay方式,是将此task放到queue的尾部,
  //若前面有耗时操作,不一定能准时执行

  new Future(() => print('cxb #3 of 4'))
      .then((_) => new Future(() => print('cxb #3a (a new cxb)')))
      .then((_) => print('cxb #3b'));

  new Future(() => print('cxb #4 of 4')).then((_) {
    return new Future(() => print('cxb #4a'));
  }).then((_) => print('cxb #4b'));
}

打印:
flutter: cxb #3 of 4
flutter: cxb #4 of 4
flutter: cxb #3a (a new cxb)
flutter: cxb #3b
flutter: cxb #4a
flutter: cxb #4b

可以看到由于return 一个Future,导致 cxb #4a延后了。

得出结论

1、Future.delayed需要延迟执行的,是在延迟时间到了之后才将此task加到event queue的队尾,所以万一前面有很耗时的任务,那么你的延迟task不一定能准时运行。
2、Future.then每次都会返回一个Future,默认是其本身。如果在then中函数也返回一个新的Future,则新Future会重新加入到event queue中等待执行
3、一个event task运行完后,会先去查看Micro queue里有没有可以执行的micro task。没有的话,在执行下一个event task

------------------------------------------------------------------------------------------------------------------------------

类似于ios中dispatch_group效果组合

void futureTest() {
  print("future start");
  Future.wait([
// 2秒后返回结果
    Future.delayed(new Duration(seconds: 5), () {
      print("hello");
      return "hello";
    }).whenComplete(() => print('hello event 执行完成')),
// 4秒后返回结果
    Future.delayed(new Duration(seconds: 6), () {
      print("world");
      return " world";
    }).whenComplete(() => print('world event 执行完成')),
  ]).then((results) {
// 上面的两个任务执行完毕后进入
    print("future finish $results");
  }).catchError((e) {
// 执行失败会走到这里
    print(e);
  }).whenComplete(() {
// 无论成功或失败都会走到这里
    print('hello world 执行完成');
  });
}


flutter: hello
flutter: hello event 执行完成
flutter: world
flutter: world event 执行完成
flutter: future finish [hello,  world]
flutter: hello world 执行完成

二、isolate

1、能互相通信

_testIsolate() async {
    ReceivePort rp1 = new ReceivePort();
    SendPort port1 = rp1.sendPort;
    // 通过spawn新建一个isolate,并绑定静态方法
    Isolate newIsolate = await Isolate.spawn(doWork, port1);
 
    SendPort port2;
    rp1.listen((message) {
      print("rp1 收到消息: $message"); //2.  4.  7.rp1收到消息
      if (message[0] == 0) {
        port2 = message[1]; //得到rp2的发送器port2
      } else {
        if (port2 != null) {
          print("port2 发送消息");
          port2?.send([1, "这条信息是 port2 在main isolate中 发送的"]); // 8.port2发送消息
        }
      }
    });
 
    print("port1--main isolate发送消息");
    port1.send([1, "这条信息是 port1 在main isolate中 发送的"]); //1.port1发送消息
 
    // newIsolate.kill();
  }
 
// 新的isolate中可以处理耗时任务
  static void doWork(SendPort port1) {
    ReceivePort rp2 = new ReceivePort();
    SendPort port2 = rp2.sendPort;
    rp2.listen((message) {
      //9.10 rp2收到消息
      print("rp2 收到消息: $message");
    });
    // 将新isolate中创建的SendPort发送到main isolate中用于通信
    print("port1--new isolate发送消息");
    port1.send([0, port2]); //3.port1发送消息,传递[0,rp2的发送器]
    // 模拟耗时5秒
    sleep(Duration(seconds: 5));
    print("port1--new isolate发送消息");
    port1.send([1, "这条信息是 port1 在new isolate中 发送的"]); //5.port1发送消息
    print("port2--new isolate发送消息");
    port2.send([1, "这条信息是 port2 在new isolate中 发送的"]); //6.port2发送消息
  }
 
//I/flutter (14639): port1--main isolate发送消息
//I/flutter (14639): rp1 收到消息: [1, 这条信息是 port1 在main isolate中 发送的]
//I/flutter (14639): port1--new isolate发送消息
//I/flutter (14639): rp1 收到消息: [0, SendPort]
//I/flutter (14639): port1--new isolate发送消息
//I/flutter (14639): port2--new isolate发送消息
//I/flutter (14639): rp1 收到消息: [1, 这条信息是 port1 在new isolate中 发送的]
//I/flutter (14639): port2 发送消息
//I/flutter (14639): rp2 收到消息: [1, 这条信息是 port2 在new isolate中 发送的]
//I/flutter (14639): rp2 收到消息: [1, 这条信息是 port2 在main isolate中 发送的]
 

其实就是需要把rootIsolate和新建的newisolate各自的SendPort传递给对方,让双方都持有SendPort,这样才能通过自己的SendPort发送消息给对应的ReceivePort

2、dynamic result = await receivePort.first; 只能收第一条信息

 _testIsolate() async {
    ReceivePort rp1 = new ReceivePort();
    SendPort port1 = rp1.sendPort;
    // 通过spawn新建一个isolate,并绑定静态方法
    Isolate newIsolate = await Isolate.spawn(doWork, port1);
 
    SendPort port2;
    dynamic receiveMsg = await rp1.first; //只拿到第一条收到结果
    print('rp1 收到消息--$receiveMsg');
    if (receiveMsg is SendPort) {
      SendPort port2 = receiveMsg;
      // print('rp1 收到消息--port2');
      port2.send([1, "这条信息是 port2 在main isolate中 发送的"]);
    }
 
    // newIsolate.kill();
  }
 
// 新的isolate中可以处理耗时任务
  static void doWork(SendPort port1) {
    ReceivePort rp2 = new ReceivePort();
    SendPort port2 = rp2.sendPort;
    rp2.listen((message) {
      print("rp2 收到消息-- $message");
    });
    // 将新isolate中创建的SendPort发送到main isolate中用于通信
    print("port1--new isolate发送消息--port2");
    port1.send(port2);
    // 模拟耗时5秒
    sleep(Duration(seconds: 5));
    print("port1--new isolate发送消息--啊哈哈");
    port1.send("啊哈哈");
  }

//flutter: port1--new isolate发送消息--port2
//flutter: rp1 收到消息--SendPort
//flutter: port1--new isolate发送消息--啊哈哈
//flutter: rp2 收到消息-- [1, 这条信息是 port2 在main isolate中 发送的]
dynamic receiveMsg = await rp1.first相当于一次性连接,后边的 port1.send("啊哈哈");其实并没有收到。

3、解决问题示例

1.创建isolate
2.打通两个isolate的通道(能互相发送消息)
3.main isolate将要计算的最大数传递给new isolate; newisolate计算,计算完成后,将结果发送回 main isolate

calculation(int n, Function(int result) success) async {
    //创建一个ReceivePort
    final receivePort1 = new ReceivePort();
    //创建isolate
    Isolate isolate = await Isolate.spawn(createIsolate, receivePort1.sendPort);
    receivePort1.listen((message) {
      if (message is SendPort) {
        SendPort sendPort2 = message;
        sendPort2.send(n);
      } else {
        print(message);
        success(message);
      }
    });
  }
 
  //创建isolate必须要的参数
  static void createIsolate(SendPort sendPort1) {
    final receivePort2 = new ReceivePort();
    //绑定
    print("sendPort1发送消息--sendPort2");
    sendPort1.send(receivePort2.sendPort);
    //监听
    receivePort2.listen((message) {
      //获取数据并解析
      print("receivePort2接收到消息--$message");
      if (message is int) {
        num result = summ(message);
        sendPort1.send(result);
      }
    });
  }
 
  //计算0到 num 数值的总和
  static num summ(int num) {
    int count = 0;
    while (num > 0) {
      count = count + num;
      num--;
    }
    return count;
  }

4、receivePort.first只能接收第一次消息怎么办?

static Future<dynamic> calculation(int n) async {
    //创建一个ReceivePort
    final receivePort1 = new ReceivePort();
    //创建isolate
    Isolate isolate = await Isolate.spawn(createIsolate, receivePort1.sendPort);
 
    //使用 receivePort1.first 获取sendPort1发送来的数据
    final sendPort2 = await receivePort1.first as SendPort;
    print("receivePort1接收到消息--sendPort2");
    //接收消息的ReceivePort
    final answerReceivePort = new ReceivePort();
    print("sendPort2发送消息--[$n,answerSendPort]");
    sendPort2.send([n, answerReceivePort.sendPort]);
    //获得数据并返回
    num result = await answerReceivePort.first;
    print("answerReceivePort接收到消息--计算结果$result");
    return result;
  }
 
  //创建isolate必须要的参数
  static void createIsolate(SendPort sendPort1) {
    final receivePort2 = new ReceivePort();
    //绑定
    print("sendPort1发送消息--sendPort2");
    sendPort1.send(receivePort2.sendPort);
    //监听
    receivePort2.listen((message) {
      //获取数据并解析
      print("receivePort2接收到消息--$message");
      final n = message[0] as num;
      final send = message[1] as SendPort;
      //返回结果
      num result = summ(n);
      print("answerSendPort发送消息--计算结果$result");
      send.send(result);
    });
  }
 
  //计算0到 num 数值的总和
  static num summ(int num) {
    int count = 0;
    while (num > 0) {
      count = count + num;
      num--;
    }
    return count;
  }

5、isolate的暂停、恢复、结束

    //恢复 isolate 的使用
    isolate.resume(isolate.pauseCapability);
 
    //暂停 isolate 的使用
    isolate.pause(isolate.pauseCapability);
 
    //结束 isolate 的使用
    isolate.kill(priority: Isolate.immediate);
 
    //赋值为空 便于内存及时回收
    isolate = null;

三、更简洁的创建isolate

import 'package:flutter/foundation.dart';
import 'dart:io';

// 创建一个新的Isolate,在其中运行任务doWork
create_new_task() async{
  var str = "New Task";
  var result = await compute(doWork, str);
  print(result);
}

static String doWork(String value){
  print("new isolate doWork start");
  // 模拟耗时5秒
  sleep(Duration(seconds:5));
  print("new isolate doWork end");
  return "complete:$value";
}

TextButton(
                child: Text('flutter创建isolate'),
                onPressed: () async {
                  num result = await compute(summ, 10000000000);
                  content = "计算结果$result";
                  setState(() {});
                },
              ),


  //计算0到 num 数值的总和
  static num summ(int num) {
    int count = 0;
    while (num > 0) {
      count = count + num;
      num--;
    }
    return count;
  }

四、封装管理

import 'dart:isolate';
typedef LikeCallback = void Function(Object value);

class  ThreadManagement  {
  //entryPoint 必须是静态方法
  static Future<Map>  runTask (void entryPoint(SendPort message), LikeCallback(Object value),{Object parameter})async{
    final response = ReceivePort();
    Isolate  d =  await Isolate.spawn(entryPoint, response.sendPort);
    // 调用sendReceive自定义方法
    if(parameter!=null){
      SendPort sendPort = await response.first;
      ReceivePort receivePort = ReceivePort();
      sendPort.send([parameter, receivePort.sendPort]);
      receivePort.listen((value){
        receivePort.close();
        d.kill();
        LikeCallback(value);
      });
      return {
        'isolate': d,
        "receivePort":receivePort,
      };
    }else{
      response.listen((value){
        response.close();
        d.kill();
        LikeCallback(value);
      });
      return {
        'isolate': d,
        "receivePort":response,
      };
    }
  }
}


// 无参数的任务
static void getNoParamTask(SendPort port) async {
    var c = await Future.delayed(Duration(seconds: 1), () {
      return "banner data";
    });
    port.send(c);
  }

// 需要参数的任务
static getParamsTask(SendPort port) async {
    ReceivePort receivePort = ReceivePort();
    port.send(receivePort.sendPort);
    // 监听外界调用
    await for (var msg in receivePort) {
      Map requestURL =msg[0];
      SendPort callbackPort =msg[1];
      receivePort.close();
      var res = await Future.delayed(Duration(seconds: 1), () {
        var requestUrl = requestURL["type"];
        var after = requestURL["after"];
        return "url = $requestUrl, after = $after";
      });
      callbackPort.send(res);
   }
}

调用

// 调用无参数的任务
ThreadManagement.runTask(API.getNoParamTask, (value){
     if(value != null){
        //业务逻辑
        print(value);
    }
});

//调用有参数的任务
ThreadManagement.runTask(API.getParamsTask,  (value){
    if(value != null){
        //业务逻辑
       print(value);
   }
}, parameter: {
    "type":"hot",
    "after":"1"
});

五、官方提供的isolate库

isolate: ^2.0.3

我们可以通过 LoadBalancer 创建出指定个数的 isolate。

Future<LoadBalancer> loadBalancer = LoadBalancer.create(2, IsolateRunner.spawn);

 这段代码将会创建出一个 isolate 线程池,并自动实现了负载均衡。

void testBalancer() async {
   final lb = await loadBalancer;
   int res = await lb.run(doWork, 110);
   print(res);
}

int doWork(int value) {
// 模拟耗时5秒
  print("new isolate doWork start");
  sleep(Duration(seconds: 5));
  return value;
}

//打印数据
new isolate doWork start
110

我们还是需要传入一个 function 在某个 isolate 中运行,并传入其参数 argument。run 方法将会返回我们执行方法的返回值。
整体和 compute 使用上差不多,但是当我们多次使用额外的 isolate 的时候,不再需要重复创建了。
并且 LoadBalancer 还支持 runMultiple,可以让一个方法在多线程中执行。
LoadBalancer 经过测试,它会在第一次使用其 isolate 的时候初始化线程池。
当应用打开后,即使我们在顶层函数中调用了 LoadBalancer.create,但是还是只会有一个 Isolate。
当我们调用 run 方法时,才真正创建出了实际的 isolate。

ARM一致性总线CMN600AE 是基于Mesh拓扑结构,对外支持AMBA CHI/ACE-LITE等接口,内部改用路由结构转发数据,并提供硬件一致性和系统缓存,还支持多芯片互联。CMN600在T16FFC上可以做到2Ghz,另外AE版本增加了车规芯片的安全功能,总线内部采用EDC检查,接口采用的奇校验。CMN-600AE具有以下特点:该网络符合功能安全标准,例如ISO 26262(汽车电子领域的功能安全标准)或IEC 61508(工业自动化领域的功能安全标准)等。 阅读详情

相关推荐

【重磅干货】介质损耗因数(tanδ)揭秘:如何精准定位材料劣化最严重的温度?附权威研究PDF!

是评估绝缘材料性能的核心指标,能直接反映材料内部能量损耗和微观结构变化。通过分析tanδ-温度曲线的峰值点,可精准定位材料劣化最严重的温度。:极化损耗峰值的温度点(如环氧树脂的80℃)是材料性能拐点,需重点关注!:图3对比了5种材料的tanδ-温度曲线,峰值温度差异高达50℃!在电力设备、电子元器件等领域,材料的老化与温度密切相关。:[《介质损耗峰值温度在设备寿命预测中的应用》]在不同温度下测量tanδ,绘制曲线图。:[《多材料介质损耗峰值温度对比研究》]:基于tanδ峰值温度开发的。

mubiao05的博客 1350

深入理解Flutter中的Future.microtask()方法及示例解析

是一个用于在微任务队列中执行函数的方法。微任务是一种高优先级的任务,在当前事件循环中的宏任务执行完毕后立即执行。因此,使用可以确保任务在当前事件循环中的特定时机被优先执行,而不必等待宏任务队列中的其他任务。通过使用方法,我们可以更加精确地控制异步任务的执行时机,提高应用程序的性能和用户体验。在开发过程中,合理地利用微任务队列可以避免一些潜在的问题,并使代码更加可靠。希望本文能够帮助你更深入地理解和应用方法,从而更加高效地处理异步任务。

爱喝水程序员的博客 1481

il2cpp分析-gobal-metadata.dat解密

打开ida,把libil2cpp拖到ida中按快捷键Shift+F12等待字符串分析完后,搜索global-metadata.dat。ida中双击sub_57EE7C进入,VS code中也跳转到LoadMetadataFile函数。VSCode打开il2cpp源代码,全局搜索global-metadata.dat。工具:010Editor,IDA 7.5,Jadx,VS Code。判断加密逻辑为根据文件的长度循环读取字节码做亦或加密。双击搜索出来的结果,切记要选il2cpp目录下的。

Android_machong的博客 8024

Flutter 事件机制 - Future 和 MicroTask 全解析

写在前面 了解过Flutter的同学都知道,不同于 Android 原生开发,dart 是单线程实体的语言,所以我们一般的异步操作,实际上还是通过单线程通过调度任务优先级来实现的,就是我们经常用到的 Future,但是Flutter中的事件机制究竟是怎样的?多个Future 和 Microtask 程序的执行顺序是怎样的? 本文将借助两个比较复杂的例子来详细介绍 Flutter 的事件机制,希望能...

weixin_33882452的博客 829

ethercat linux lan9252 - lan9253调试

linux 的ethercat测试

linsheng_111的专栏 1934

11. 使用 HTTP PUT, PATCH 以及 MERGE 请求消费 SAP ABAP OData 服务修改操作的实现及其区别

使用 SAP ABAP SEGW 事物码实现 OData 服务的修改操作时,对于消费端通过 PATCH/MERGE 和 PUT 这三种不同类型的 HTTP 请求触发的场景,我们应该在 UPDATE_ENTITY 方法里用 IF 分支分别进行处理,原因就在于 GET_ENTITY 方法是否在修改处理逻辑的过程中被触发。......

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 2460

Flutter Future.microtask作用

Flutter 中的 Future.microtask 方法可以将回调函数放到下一个事件循环中执行。这意味着在当前函数执行完毕之后,它会将回调函数放到事件队列的末尾,等待下一次事件循环时执行。这对于在函数中异步执行操作,并在操作完成后立即调用回调函数时非常有用。 例如: Future.microtask(() => print('microtask')); print('main'); 输...

weixin_42584586的博客 364

SAP SD模块定价过程后台配置简介

只有手工输入定价时(例如,在定价中的定价浏览屏幕中),或者只有从外部处理转移这些定价时(例如,成本核算),才将这些定价包括在确定(价格确定、输出确定,批次确定)之中。定价过程的定义和分配是SD模块中最核心的配置,包含了条件表、条件类型、存取顺序、发票类型、客户定价过程等,确定了销售订单已什么价格销售、税率、附加折扣等多个条件行程有一个定价过程。12、小计:记录该条件类型在VBAP表中是否存储,以及其后续用途,如记入信贷,占用信贷额度,记入成本等,如果需要金额暂用信贷额度的话,在小计这里选择A即可。

我小时候很黑的博客 3782

自己动手敲future模式例子

自己动手敲future模式例子 1.future设计模式简介: future设计模式的核心思想是异步调用。其理念应该跟ajax差不多,就是希望在等一个耗时比较长的操作的期间,做其他操作,然后其他操作做完了,回来再处理这个耗时长的操作的结果。这样业务完成的效率高一些。 2.future设计模式实现时序图: 通过看以下时序图,来了解future设计模式的具体实现思路。...

区生生的博客 668

使用Qt和MX Component插件实现与菱PLC的通信

在本文中,我们介绍了如何使用Qt和MX Component插件实现与菱PLC的通信。我们首先安装和配置了MX Component插件,并在Qt项目中初始化和使用MX Component来连接、读取和写入PLC的数据。安装完成后,您需要在Qt项目中配置MX Component的路径,以便Qt可以找到所需的库文件。在本文中,我们将探讨如何使用Qt和MX Component插件来实现与菱PLC的通信。在主函数中,我们将初始化MX Component,并创建一个与PLC通信的示例。在上面的代码中,我们使用了。

TlScratch的博客 996

【参数配置】OpenClaw 的破解之道(Doom Loop)

本文深入解析了OpenClaw中的Doom Loop(死循环)问题及其应对策略。主要内容包括: Agent Loop的核心概念:基于ReAct范式,OpenClaw通过"思考-行动-观察"循环执行任务,但可能陷入无进展的死循环。 Doom Loop现象:Agent持续执行但任务进度为零,常见于四种工具调用场景:相同调用重复执行、调用不存在工具、轮询工具卡死、操作交替振荡。 OpenClaw的防御机制: 第一道防线:重试端断路器,通过上下文压缩熔断(最多3次)和总重试次数熔断(32-160次)防止无限重试。

海兰 4042

future例子

import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionExcepti

嘻嘻哈哈的专栏 537

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

java future 例子_java Future/Callable说明及例子

packagecom.bjsxt.test;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Future;/** Callable 和 Future接口* Cal...

weixin_39814088的博客 108

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

java future 例子_javaCallable与Future的详解及实例

java Callable与FutureCallable与 Future 两功能是Java在后续版本中为了适应多并法才加入的,Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其他线程执行的任务。Callable的接口定义如下;public interface Callable {V call() throws Exception;}...

weixin_30800615的博客 337

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Java Callable Future Example(java 关于Callable,Future的例子)

Home » Java » Java Callable Future ExampleJava Callable Future Example April 3, 2018 by Pankaj 25 Comments Java Callable and Future are used a lot in multithreaded programming. In last few p...

WGH100817的博客 401

callable和future的小例子

package cn.javass.spring.chapter12; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.co...

复兴斧头帮 267

Callable Future FutureTask 使用例子

package future; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class UseFuture { /...

dzh145的专栏 370

java future 例子_20个使用 Java CompletableFuture的例子

这篇文章介绍 Java 8 的 CompletionStage API和它的标准库的实现 CompletableFuture。API通过例子的方式演示了它的行为,每个例子演示一到两个行为。既然CompletableFuture类实现了CompletionStage接口,首先我们需要理解这个接口的契约。它代表了一个特定的计算的阶段,可以同步或者异步的被完成。你可以把它看成一个计算流水线上的一个单元,...

weixin_42371234的博客 436

设计模式之Future模式例子

在我认为,实例教学比理论教学更加容易理解,并且理论知识网上一大堆,这里就不重复了,所以记录下Future模式的一种实现例子,以备以后可以查看。 如果不太懂Future模式时干什么的,最好先普及下理论知识再来看更好。 好,现在我们就开始来讲解分析我的例子: 首先需要定义的就是输入和输出参数的格式,这里简单的创建了一个如下: public class Result {

知足happiness的博客 1525

Executor 和 Future 的例子

在互联网应用的开发中,为了提高应用的响应速度,可以尝试将一个任务拆分为多个子任务并发执行,然后将子任务的处理结果进行合并(有点类似MapReduce的意思)。 Java1.5之后的 concurrent 包中提供了Executor和Future,可以实现这样的功能。   比如把一个大文件拆分成10个小文件(拆分过程省略),然后使用10个线程把文件写入HDFS。   package exa

wanghy1979的专栏 987

java future 和 callable的一个例子

package test; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.

Flyer的后花园 960

Python future模块小例子

按照官方的解释,至少确保在2.1之前版本的Python可以正常运行一些新的语言特性,需要使用语句 ‘from future import *’。举例来说:#Enable nested scopes in Python 2.1 from __future__ import nested_scopes 如果使用这个语句,则该语句必须是模块或程序的第一个语句。此外,'__ future__' 模块中存

u012727303的专栏 1878

java future接口_java中future 接口 异步转为同步例子

java中future 接口 异步转为同步例子文章给大家介绍了一个实用的例子,希望例子能帮助到各位。 代码如下 复制代码 import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.Execut...

weixin_31845243的博客 290

两个例子解释Callable 和 Future接口

Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。Callable和Runnable有几点不同: Callable规定的方法是call(),而Runnable规定的方法是run(). Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。 call()方法可抛出异常,而run()方法是不能抛出异常的。 运行Callable任务可拿到一个Future对象,通过Future对象可了解任务执行情况,可取

zhulin1028的博客 586
上一篇: 如果有两个Xcode,Flutter如何选择
下一篇: 记一次Android studio卡在启动页
史蒂芬-周
博客等级 码龄9年 5粉丝 50原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值