1.延時(shí)器
// 主線程調(diào)用
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5.0) {
print("5 秒后輸出", Thread.current.isMainThread)
}
// 5 秒后輸出 true
2.異步執(zhí)行回主線程寫(xiě)法
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("第二組失敗")
}
// 結(jié)束
group.notify(queue: DispatchQueue.main) {
print("全部執(zhí)行完成")
}
/*
第二組成功
第一組成功
全部執(zhí)行完成
*/
4.信號(hào)量(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("第二組失敗")
}
}
// 結(jié)束
queue.async {
semaphore.wait()
AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-1.json", success: { (json) in
semaphore.signal()
print("全部執(zhí)行完成")
}) { (error) in
semaphore.signal()
print("全部執(zhí)行完成")
}
}
/*
queue.async {
semaphore.wait()
DispatchQueue.main.async {
print("全部執(zhí)行完成")
semaphore.signal()
}
}
*/
/*
第一組成功
第二組成功
全部執(zhí)行完成
*/