我实现了以下类:
class:
class GCDStudy {
func asyncSerial(time:Double){
let queue = dispatch_queue_create("DISPATCH_QUEUE_SERIAL",DISPATCH_QUEUE_SERIAL)
dispatch_async(queue){
var i:Double = 0
while(i < 3){
i++
print("asyncSerial -wait:\(time)-\(i)")
}
}
}
func asyncConcurrent(time:Double){
let queue = dispatch_queue_create("DISPATCH_QUEUE_CONCURRENT",DISPATCH_QUEUE_CONCURRENT)
dispatch_async(queue){
var i:Double = 0
while(i < 3){
i++
print("asyncConcurrent -wait:\(time)-\(i)")
}
}
}
}
请按以下方式运行:
运行A:
gCDStudy = GCDStudy()
gCDStudy.asyncSerial(1)
gCDStudy.asyncSerial(2)
运行 B
vgCDStudy2 = GCDStudy()
gCDStudy2.asyncConcurrent(1)
gCDStudy2.asyncConcurrent(2)
并且结果是RunA:
asyncSerial -wait:1.0-1.0
asyncSerial -wait:2.0-1.0
asyncSerial -wait:1.0-2.0
asyncSerial -wait:2.0-2.0
asyncSerial -wait:1.0-3.0
asyncSerial -wait:2.0-3.0
运行B的结果:
asyncSerial -wait:1.0-1.0
asyncSerial -wait:2.0-1.0
asyncSerial -wait:1.0-2.0
asyncSerial -wait:2.0-2.0
asyncSerial -wait:1.0-3.0
asyncSerial -wait:2.0-3.0
这些结果是相同的,它们之间有什么不同?
有时候这些结果是不同的。
谢谢
dispatch_async
的调用放在循环内部。 - rmaddy