iOS中。苹果提供了两张方法实现多任务处理
- GCD (Grand Central Dispatch)
- NSOperationQueue 框架
GCD 简单示例
例1:
//创建一个队列
let queue = DispatchQueue(label: "com.test.myqueue")
//在队列' queue' 中同步打印0~10
queue.sync {
for i in 0...10 {
print("❤️",i)
}
}
//在'main queue'中打印10~20
for i in 10...20 {
print("M",i)
}
//结果:程序会卡住,在红星代码块执行完后再执行下面的
例2
//创建一个队列
let queue = DispatchQueue(label: "com.test1.myqueue")
//在队列' queue' 中异步打印0~10
queue.async {
for i in 0...50 {
print("❤️",i)
}
}
//在'main queue'中打印10~500
for i in 10...500 {
print("M",i)
}
//结果: 两个代码块并发执行
GCD队列 优先级
从上到下,优先级从高到低:
- userInteractive
- userInitiated
- default
- utility
- background
- unspecified
例1:
//两个队列优先级相同
let queue1 = DispatchQueue(label: "test1", qos: .userInteractive)
let queue2 = DispatchQueue(label: "test2", qos: .userInteractive)
queue1.async {
for i in 0...10 {
print("🍌",i)
}
}
queue2.async {
for i in 0...10 {
print("❤️",i)
}
}
// 结果:大致会"均匀交叉"执行两个代码块
//两个队列优先级不相同
let queue1 = DispatchQueue(label: "test1", qos: .background)
let queue2 = DispatchQueue(label: "test2", qos: .userInteractive)
queue1.async {
for i in 0...10 {
print("🍌",i)
}
}
queue2.async {
for i in 10...20 {
print("❤️",i)
}
}
// 结果:下面的代码块先执行(测试发现这个好像并不稳定~~~)
并发队列
let queue = DispatchQueue(label: "test",qos: .utility)
queue.async {
for i in 0..<10 {
print("❤️",i)
}
}
queue.async {
for i in 0..<10 {
print("🍌",i)
}
}
//结果 按顺序执行
let queue = DispatchQueue(label: "test",qos: .utility, attributes:.concurrent)
queue.async {
for i in 0..<10 {
print("❤️",i)
}
}
queue.async {
for i in 0..<10 {
print("🍌",i)
}
}
//结果 两个代码块并发执行
手动执行
attributes:.initiallyInactive,这样队列不会自动执行,需要手动触发queue.activate() :手动触发
attributes:[.concurrent,.initiallyInactive] 并发+手动触发:
延迟执行
let delayQueue = DispatchQueue(label: "test",qos: .userInitiated)
print(Date())
let time:DispatchTimeInterval = .seconds(2)
delayQueue.asyncAfter(deadline: .now() + time) {
print(Date())
}
let delayQueue = DispatchQueue(label: "test",qos: .userInitiated)
print(Date())
delayQueue.asyncAfter(deadline: .now() + 2) {
print(Date())
}
DispatchWorkItem
DispatchWorkItem是一个代码块,它可以被分到任何的队列