Flutter时钟实现线程池Compute操作 多线程 改良

代码水平有限 只能想到用timmer定时处理添加线程池

代码如下 是多线程compute处理下载某个文件

Timer.periodic(new Duration(milliseconds: waitMilSeconds), (timer) async {//原来左边有个回调timer
      if(i<downloadUrlList.length-1){//还没下完
        if(currentThreadNum<maxThreadNum){
          
          i++;
          currentThreadNum++;
          print('总线程数:${currentThreadNum}/${maxThreadNum} 正在下载第$i个Bgm');
          List paramsList=[downloadUrlList[i],downInfoMap,i];
          await doComputeDownThread(paramsList);
          currentThreadNum--;
        }else{
          print('线程已超过${maxThreadNum} 正在等待');
        }
      }else{//下完后关闭定时器
        print('已经下载完毕');
        timer.cancel();
      }
    });

1.也可以用while实现  然后当线程数小于设置的Max时候选择flutter delay延迟

改良版  改良版解决了一直卡在最大线程数-1 不动问题

i=0;
    List idList=idClientPairMap.keys.toList();
    List clientList=idClientPairMap.values.toList();
    length=idList.length;
    currentThreadNum=0;
    maxThreadNum=Configure.DownloadMaxThreadNum;  //我设置7   4核8线程cpu
    waitMilSeconds=Configure.DownloadTimmerMiliSeconds; //无法中途更改时钟?速度 这里没用到

    while(i<length-1){

      if(currentThreadNum<0){
        currentThreadNum=0;
      }
      if(currentThreadNum<maxThreadNum){
        String mid=idList[i];
        String client=clientList[i];

        i++;
        String mainUrl='https://maplestory.io/api/${client}map';
        String url = '${mainUrl}/${mid}/bgm';

        List params=[file,url,mid];
        double randomTime = Random().nextDouble();
        int ran=(randomTime*1000*300).floor(); 
        //设置随机偏移时间   不会同时操作导致  currentThreadNum同时++或者--
        await Future.delayed(Duration(microseconds:ran));
        currentThreadNum++;
        print('正在下载第$i/${length}个Map映射url ${mid}->${client}  总线程数:${currentThreadNum}/${maxThreadNum} ');
        compute(doComputeWriteRedirectUrl,params).then((int value) async {

          double randomTime = Random().nextDouble();
          int ran=(randomTime*1000*300).floor();
          await Future.delayed(Duration(microseconds:ran));
          //可以吗 防止同时修改
          currentThreadNum--;
        }).onError((error, stackTrace) {
          print('${error} ${stackTrace}' );
              currentThreadNum--;
        });
      }else{
        await Future.delayed(Duration(milliseconds: 1000));
        print('线程已超过${maxThreadNum} 正在等待');
      }

    }
    print('结束了!');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值