Swift GCD详解
2019-11-19 本文已影响0人
浅宇落
1.延时器
// 主线程调用
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5.0) {
print("5 秒后输出", Thread.current.isMainThread)
}
// 5 秒后输出 true
2.异步执行回主线程写法
DispatchQueue.global().async {
print("async do something\(Thread.current)")
DispatchQueue.main.async {
print("come back to main thread\(Thread.current)")
}
}
/*
async do something<NSThread: 0x600002f7e6c0>{number = 3, name = (null)}
come back to main thread<NSThread: 0x600002f27c80>{number = 1, name = main}
*/
3. DispatchGroup(线程组)
let group = DispatchGroup()
// 第一组
group.enter()
AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-500.json", success: { (json) in
group.leave()
print("第一组成功")
}) { (error) in
group.leave()
print("第一组失败")
}
// 第二组
group.enter()
AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-10.json", success: { (json) in
group.leave()
print("第二组成功")
}) { (error) in
group.leave()
print("第二组失败")
}
// 结束
group.notify(queue: DispatchQueue.main) {
print("全部执行完成")
}
/*
第二组成功
第一组成功
全部执行完成
*/
4.信号量(DispatchSemaphore)
let semaphore = DispatchSemaphore(value: 1)
let queue = DispatchQueue(label: "L?II")
// 第一组
queue.async {
semaphore.wait()
AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-100.json", success: { (json) in
semaphore.signal()
print("第一组成功")
}) { (error) in
semaphore.signal()
print("第一组失败")
}
}
// 第二组
queue.async {
semaphore.wait()
AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-100000.json", success: { (json) in
semaphore.signal()
print("第二组成功")
}) { (error) in
semaphore.signal()
print("第二组失败")
}
}
// 结束
queue.async {
semaphore.wait()
AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-1.json", success: { (json) in
semaphore.signal()
print("全部执行完成")
}) { (error) in
semaphore.signal()
print("全部执行完成")
}
}
/*
queue.async {
semaphore.wait()
DispatchQueue.main.async {
print("全部执行完成")
semaphore.signal()
}
}
*/
/*
第一组成功
第二组成功
全部执行完成
*/