1. 程式人生 > >[Swift通天遁地]四、網路和執行緒-(3)執行緒組:使用DispatchGroup(排程組)對執行緒進行分組管理

[Swift通天遁地]四、網路和執行緒-(3)執行緒組:使用DispatchGroup(排程組)對執行緒進行分組管理

本文將演示執行緒組的使用。

使用執行緒組可以設定在完成一個或一組任務之後,再執行另一個或一組任務。

在專案導航區,開啟檢視控制器的程式碼檔案【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 }

當排程組中的任務全部執行完成之後,才會執行排程組的通知方法。