Dart Flutter中如何实现多线程

发布于 1周前 作者 itying888 最后一次编辑是 5天前 来自 分享

Dart 是单线程语言,在 Dart 中,没有多线程。Dart 的单线程模型和异步编程工具已经能够满足常见的并发需求。

但是我们可以使用异步模拟多线程或者使用isolate并发模型实现类似多线程的功能。

您也可以学习Flutter+Getx仿小米实战系列教程https://www.itying.com/category-88-b0.html

方法1:利用异步,模拟多线程 方法2: 利用dart:isolate实现

import 'dart:isolate';

void main(List<String> args) {
  // 开启一个并发线程
  Isolate.spawn(cldc1, 1000000);
// 开启一个并发线程
  Isolate.spawn(cldc2, 100);
  print('end');
}

void cldc1(int count) {
  int tolte = 0;
  for (int i = 0; i < count; i++) {
    tolte = tolte + i;
  }
  print(tolte);
}

void cldc2(int count) {
  int tolte = 0;
  for (int i = 0; i < count; i++) {
    tolte = tolte + i;
  }
  print(tolte);
}

输出: end 4950 499999500000

回到顶部