赞
踩
GCD常用的用法
子线程
- DispatchQueue.global().async {
- print("开一条全局队列异步执行任务")
- }
- DispatchQueue.main.async {
- print("在主队列执行任务")
- }
wait
- var myQueue = DispatchQueue(label: "第一条线程")
- var myQueue2 = DispatchQueue(label: "第二条线程")
- let group = DispatchGroup()
-
- myQueue.async(group: group, qos: .default, flags: []) {
- for _ in 0...10 {
-
- print("耗时任务一")
- }
- }
-
- myQueue.async(group: group, qos: .default, flags: []) {
- for _ in 0...10 {
-
- print("耗时任务二")
- sleep(UInt32(3))
- }
- }
- //等待上面任务执行,会阻塞当前线程,超时就执行下面的,上面的继续执行。可以无限等待 .distantFuture
- let result = group.wait(timeout: .now() + 2.0)
- switch result {
- case .success:
- print("不超时, 上面的两个任务都执行完")
- case .timedOut:
- print("超时了, 上面的任务还没执行完执行这了")
- }
-
- print("接下来的操作")
- let group = DispatchGroup()
- myQueue?.async(group: group, qos: .default, flags: [], execute: {
- for _ in 0...10 {
-
- print("耗时任务一")
- }
- })
- myQueue?.async(group: group, qos: .default, flags: [], execute: {
- for _ in 0...10 {
-
- print("耗时任务二")
- }
- })
- //执行完上面的两个耗时操作, 回到myQueue队列中执行下一步的任务
- group.notify(queue: myQueue!) {
- print("回到该队列中执行")
- }
barrier
- myQueue?.async {//任务一
- for _ in 0...10 {
- print("......")
- }
- }
- myQueue?.async {//任务二
- for _ in 0...10 {
- print("++++++");
- }
- }
-
- // barrier 会等待上面执行完毕再执行下面的,会阻塞当前线程
- // myQueue?.async(flags:.barrier ,execute: {//1.
- // print("000000")
- // })
-
- myQueue?.async(group: nil, qos: .default, flags: .barrier, execute: {//2.
- print("000000")
- })
-
- myQueue?.async {
- print("111111")
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。