var myQueue: DispatchQueue?
var myQueueTimer: DispatchQueue?
var myTimer: DispatchSourceTimer?
var myGroup: DispatchGroup?
var mySource: DispatchSource?
//MARK: - 并行队列 没有attributes,默认是串行队列
myQueue = DispatchQueue(label: "myQueue",attributes:DispatchQueue.Attributes.concurrent)
myQueue?.async {
for _ in 0...10 {
NSLog("......")
}
}
myQueue?.async {
for _ in 0...10 {
NSLog("++++++");
}
}
//MARK: barrier 会等待上面执行完毕再执行下面的,会阻塞当前线程
myQueue?.async(flags:.barrier ,execute: {
NSLog("000000")
})
myQueue?.async {
NSLog("111111")
}
//MARK: - 信号量
//初始化信号量,计数为2
mySemaphore = DispatchSemaphore.init(value: 2)
for i in 0...10 {
NSLog("----i:%d----", i)
mySemaphore?.wait() //获取信号量,信号量减1,为0时候就等待,会阻碍当前线程
myQueue?.async {
for j in 0...4 {
NSLog("%d++++j:%d",i, j)
}
self.mySemaphore?.signal() //释放信号量,信号量加1
}
}
//MARK: - 延时提交任务
myQueue?.asyncAfter(deadline: DispatchTime.now() + 10, execute: {
NSLog("6666")
self.stopTimer()
})
//MARK: - 串行队列 默认串行队列
myQueueTimer = DispatchQueue(label: "myQueueTimer")
myQueueTimer?.async {
for _ in 0...10 {
NSLog("aaaaaaa");
}
}
myQueueTimer?.async {
for _ in 0...10 {
NSLog("bbbbbbb");
}
}
//MARK: - 重复提交任务
// 秒 毫秒 微秒 纳秒
// 1 seconds = 1000 milliseconds = 1000,000 microseconds = 1000,000,000 nanoseconds
myTimer = DispatchSource.makeTimerSource(flags: [], queue: myQueueTimer!)
myTimer?.scheduleRepeating(deadline: .now(), interval: .seconds(1) ,leeway:.milliseconds(100))
myTimer?.setEventHandler {
NSLog("fff")
}
myTimer?.resume()
//MARK: - Group
//MARK: notify
myGroup = DispatchGroup()
myQueue?.async(group: myGroup, qos: .userInitiated, execute: {
for _ in 0...10 {
NSLog("1a1a1a1a1a1a")
}
})
myQueue?.async(group: myGroup, qos: .userInitiated, execute: {
for _ in 0...10 {
NSLog("2b2b2b2b2b2b")
}
})
//执行完上面两个任务才执行下面的这个任务,不会阻塞当前线程
myGroup?.notify(queue: myQueue!, execute: {
NSLog("3c3c3c3c3c3c")
})
NSLog("next")
//MARK: wait
myQueue?.async(group: myGroup, qos: .userInitiated, execute: {
for _ in 0...10 {
NSLog("==========")
}
})
myQueue?.async(group: myGroup, qos: .userInitiated, execute: {
for _ in 0...10 {
NSLog("------------")
}
})
//等待上面任务执行,会阻塞当前线程,超时就执行下面的,上面的继续执行。可以无限等待 .distantFuture
let result = myGroup?.wait(wallTimeout: .now()+2)
if result == DispatchTimeoutResult.success {
NSLog("ok.")
} else {
NSLog("time out.")
}
NSLog("next")
//MARK: enter leave 手动管理group计数,enter和leave必须配对
myGroup?.enter()
myQueue?.async(){
for _ in 0...10 {
NSLog("+++++++++++++")
}
self.myGroup?.leave()
}
myGroup?.enter()
myQueue?.async(){
for _ in 0...10 {
NSLog("------------")
}
self.myGroup?.leave()
}
myGroup?.notify(queue: myQueue!, execute: {
NSLog("=")
})
swift3.0 GCD
最新推荐文章于 2020-08-31 15:15:14 发布