串行队列
串行队列中的任务会按顺序执行
//串行队列
let chuanxingQueue = DispatchQueue(label: "test")
//这个任务大概用时100s完成
for item in 0...100 {
chuanxingQueue.sync {
Thread.sleep(forTimeInterval: 1)
print("串行同步",item)
}
}
并行队列
并行队列中的任务是无序执行
//并行
let bingxingQueue = DispatchQueue.global()
//这个任务大概用时1s完成
for item in 0...100 {
bingxingQueue.async {
Thread.sleep(forTimeInterval: 1)
print("并行",item)
}
}
-------------------分割线------------------------
结论:
// let bingxingQueue = DispatchQueue.global()//并行队列,里面嵌套什么都不会锁死
// let chuanxingQueue = DispatchQueue.init(label: "chuanxing")//串行队列,里面嵌套同步任务会锁死
串行队列
1、串行队列,同步任务中添加同步任务(锁死)
chuanxingQueue.sync {
print("1111111")
chuanxingQueue.sync {//这里锁死
print("2222222")
}
print("3333333")
}
报错:Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
2、串行队列中,同步任务中添加异步任务
chuanxingQueue.sync {
print("1111111")
chuanxingQueue.async {
print("2222222")
}
print("3333333")
}
3、串行队列中,异步任务加入同步任务
chuanxingQueue.async {
print("1111111")
chuanxingQueue.async {
print("222222")
}
print("3333333")
}
4、串行队列中,异步任务加入同步任务(锁死)
chuanxingQueue.async {
print("1111111")
chuanxingQueue.sync {//锁死
print("22222222")
}
print("33333333")
}
并行队列
1、异步嵌套异步任务
let bingxingQueue = DispatchQueue.global()
bingxingQueue.async {
print("111111")
bingxingQueue.async {
print("222222")
}
print("333333")
}
打印结果:
111111
333333
222222
2、异步嵌套同步任务
bingxingQueue.async {
print("1111111")
bingxingQueue.sync {
print("222222")
}
print("33333333")
}
打印结果:
1111111
222222
33333333
3、同步嵌套异步任务
bingxingQueue.sync {
print("1111111111")
bingxingQueue.async {
print("222222222")
}
print("333333333")
}
打印结果:
1111111111
333333333
222222222
4、同步嵌套同步任务
bingxingQueue.sync {
print("11111111111")
bingxingQueue.sync {
print("2222222222")
}
print("333333333")
}
打印结果:
11111111111
2222222222
333333333