• [Swift通天遁地]四、网络和线程-(3)线程组:使用DispatchGroup(调度组)对线程进行分组管理


    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/10222246.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    目录:[Swift]通天遁地Swift

    本文将演示线程组的使用。

    使用线程组可以设置在完成一个或一组任务之后,再执行另一个或一组任务。

    在项目导航区,打开视图控制器的代码文件【ViewController.swift】

    现在开始编写代码,实现线程组的功能。

     1 import UIKit
     2 
     3 class ViewController: UIViewController {
     4 
     5     override func viewDidLoad() {
     6         super.viewDidLoad()
     7         // Do any additional setup after loading the view, typically from a nib.
     8         
     9         //在控制台输出一条语句,用来标识任务的开始
    10         print("Start the task and display the Loading animation.")
    11         
    12         //初始化一个调度组对象
    13         let group = DispatchGroup()
    14         //获得全局调度队列
    15         let globalQueue = DispatchQueue.global()
    16         
    17         //通过全局调度队列的异步方法,执行调度组对象
    18         globalQueue.async(group: group, execute:  {_ in
    19             //在控制台输出一条语句,模拟一条具体的任务
    20             print("Load a user picture from the remote server.")
    21         })
    22         
    23         //通过全局调度队列的异步方法,执行调度组对象
    24         globalQueue.async(group: group, execute:  {_ in
    25             //在控制台输出一条语句,模拟一条具体的任务。
    26             //并设置该任务和第一个任务,都位于同一个调度组中。
    27             print("Get the annual record of all transactions by user id.")
    28         })
    29         
    30         //调用调度组的通知方法,当调度组中的任务全部完成之后,执行其他的任务。
    31         group.notify(queue: globalQueue, execute: {_ in
    32             print("Complete all tasks and hide the Loading animation.")
    33         })
    34         
    35         //通过全局调度队列的异步方法,执行调度组对象
    36         globalQueue.async(group: group, execute:  {_ in
    37             //并设置该任务和前面的两个任务,位于同一个调度组中,
    38             //这样当调度组中的三个任务全部执行完成之后,才会执行调度组的通知方法
    39             print("Get the collection of goods by user id.")
    40         })
    41     }
    42 
    43     override func didReceiveMemoryWarning() {
    44         super.didReceiveMemoryWarning()
    45         // Dispose of any resources that can be recreated.
    46     }
    47 }

    当调度组中的任务全部执行完成之后,才会执行调度组的通知方法。

  • 相关阅读:
    将python的代码文件打包成可执行文件
    SpringBoot整合JdbcTemplate连接Mysql
    Golang开发环境搭建
    java中的Lamdba表达式和Stream
    MySQL 优化1
    MySQL you *might* want to use the less safe log_bin_trust_function_creators variable
    MySQL mysqlbinlog
    MySQL 事件调度器
    MySQL 忘记密码解决办法
    MySQL 创建自定义函数(2)
  • 原文地址:https://www.cnblogs.com/strengthen/p/10222246.html
Copyright © 2020-2023  润新知