队列
DispatchQueue 可以执行串行,并发。FIFO
创建队列, label 唯一的标识,建议用DNS命名
let queue = DispatchQueue(label: "com.nip.queue")
同步执行: sync
func gcd_test1() {
// 创建一个队列,并给队列提供一个独一无二的标签,DNS
let queue = DispatchQueue(label: "com.newsinpalm")
// 队列创建完,就可以执行同步sync,异步操作async
queue.sync {
for i in 0 ..< 10 {
// 先打印完
print("🔴",i)
}
}
for i in 100 ..< 110 {
// 再打印
print("😷",i)
}
}
异步执行:async
let queue = DispatchQueue(label: "com.newsinpalm")
// 队列创建完,就可以执行同步sync,异步操作async
queue.async {
for i in 0 ..< 10 {
print("🔴",i)
}
}
queue.async {
for i in 100 ..< 110 {
print("😷",i)
}
}
队列的优先级
枚举类型DispatchQoS
public enum QoSClass {
case background
case utility
case `default`
case userInitiated
case userInteractive
case unspecified
public init?(rawValue: qos_class_t)
public var rawValue: qos_class_t { get }
}
优先级顺序
userInteractive
userInitiated
default
utility
background
unspecified
代码:
let queue1 = DispatchQueue(label: "com.nip.queue1", qos: DispatchQoS.default)
let queue2 = DispatchQueue(label: "com.nip.queue2", qos: DispatchQoS.userInteractive)
queue1.async {
for i in 0 ..< 10 {
print("👨❤️👨",i)
}
}
queue2.async {
for i in 100..<110{
print("👃🏻",i)
}
}
异步并发,自动执行
// 异步并发队列,自动执行
func gcd_test3() {
let anotherQueue = DispatchQueue(label: "com.nip.another", qos: .default, attributes: .concurrent)
anotherQueue.async {
for i in 0 ..< 10 {
print("🔴",i)
}
}
anotherQueue.async {
for i in 100..<110{
print("🌘",i)
}
}
}
异步并发,手动执行,必须引用queue
let anotherQueue = DispatchQueue(label: "com.nip.another", qos: .userInitiated, attributes: [.concurrent,.initiallyInactive])
queue = anotherQueue
anotherQueue.activate()
anotherQueue.async {
for i in 0 ..< 10 {
print("🎾",i)
}
}
anotherQueue.async {
for i in 100..<110{
print("🏐",i)
}
}
anotherQueue.async {
for i in 100..<110{
print("🏉",i)
}
}
延迟执行
print(Date())
let queue = DispatchQueue(label: "com.nip.delay", qos: .userInitiated)
queue.asyncAfter(deadline: .now() + 3) {
print("⚽️",Date())
}
任务项 DispatchWorkItem
let workItem = DispatchWorkItem {
for i in 0 ..< 10 {
print("🔴",i)
}
}
执行任务项
let queue = DispatchQueue(label: "com.nip.queue")
queue.async(execute: workItem)
全局队列
DispatchQueue.global()
public class func global(qos: DispatchQoS.QoSClass = default) -> DispatchQueue
主队列
DispatchQueue.main
常用的姿势
DispatchQueue.global().async {
// 子线程执行
DispatchQueue.main.async(execute: {
// 主线程执行
})
}
队列组:实现某些任务执行完了,再去执行相应的任务
DispatchGroup
enter() leave() 一定要对应
let group = DispatchGroup()
group.enter()
DispatchQueue.global().async {
group.leave()
for i in 0..<10{
print(" 🏐 ",i)
}
}
group.enter()
DispatchQueue.global().async {
for i in 100..<110{
print(" 🏉 ",i)
}
group.leave()
}
group.notify(queue: DispatchQueue.main) {
for i in 1000..<1010 {
print(" 🚀 ",i)
}
}