本文主要是介绍Swift3.0 GCD多线程示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
///
func mainThread(){// 开一条全局队列异步执行任务DispatchQueue.global().async {/* Group的用法* 1. notify(依赖任务), 必须和 enter/leave在同一队列才会执行* 2. wait(任务等待)* 3. enter/leave 手动管理group计数,enter和leave必须配对, 可以不需要wait()*/let group = DispatchGroup()var subTask: [DispatchQueue] = [DispatchQueue]()/* // 主线程DispatchQueue.main.async { //通知ui刷新print("Main 刷新 UI: Begin")group.wait()Thread.sleep(forTimeInterval: 1) //停止1秒print("Main 刷新 UI: End")} // *///初始化8个子线程for i in 0...7{subTask.append(DispatchQueue(label: "subTask\(i)", attributes: .concurrent))}//启动8个子线程任务for item in subTask{group.enter() //把该任务添加到组队列中执行, enter和leave必须配对item.async(group: group) {Thread.sleep(forTimeInterval: 1) //停止1秒print("\(Date().description) subTask.label = \(item.label)")DispatchQueue.main.async(group: group, execute: refreshMainUI(dq: item)) // 通知主线程刷新UIgroup.leave() //执行完之后从组队列中移除}group.notify(queue: item){ // 对应的子线程完成后,扫尾任务print("\(item.label) finished,do something more")// *** 此处可添加 对应的子线程完成后的扫尾任务sleep(10)}}}// 通知主线程刷新UI, 有需要在主线程中执行的代码,请添加到此func refreshMainUI(dq:DispatchQueue) -> DispatchWorkItem{let workItem = DispatchWorkItem {print("Refresh main UI: \(dq.label): Hello world! ")// *** 此处可添加 UI 刷新任务Thread.sleep(forTimeInterval: 5) //停止1秒}return workItem}
}
Logs 如下:
****** Cyril Test Start ******2019-01-16 09:35:44 +0000 Main: Execute mainThread()****** Cyril Test End ******
Waitting all test done.
2019-01-16 09:35:44 +0000 subTask.label = subTask3
2019-01-16 09:35:44 +0000 subTask.label = subTask5
2019-01-16 09:35:44 +0000 subTask.label = subTask1
2019-01-16 09:35:44 +0000 subTask.label = subTask7
2019-01-16 09:35:44 +0000 subTask.label = subTask0
2019-01-16 09:35:44 +0000 subTask.label = subTask2
2019-01-16 09:35:44 +0000 subTask.label = subTask6
2019-01-16 09:35:44 +0000 subTask.label = subTask4
All test done.
Refresh main UI: subTask2: Hello world!
Refresh main UI: subTask3: Hello world!
Refresh main UI: subTask1: Hello world!
Refresh main UI: subTask0: Hello world!
subTask0 finished,do something more
subTask2 finished,do something more
subTask3 finished,do something more
subTask1 finished,do something more
subTask4 finished,do something more
Refresh main UI: subTask4: Hello world!
subTask5 finished,do something more
subTask6 finished,do something more
subTask7 finished,do something more
Refresh main UI: subTask5: Hello world!
Refresh main UI: subTask7: Hello world!
Refresh main UI: subTask6: Hello world!
最新代码放在gitlab上:
https://gitlab.com/cyril_j/mutils/blob/master/Swift/mainThread.swift
这篇关于Swift3.0 GCD多线程示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!