方法一:使用dispatch_group
dispatch_group_t group = dispatch_group_create();
for (int i=0; i<10; i++) {
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(1);
printf("i = %d", i);
dispatch_group_leave(group);
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
printf("开始执行任务A");
});
方法二: 信号量实现
let sem = DispatchSemaphore.init(value: 0)
for i in 0..<10 {
DispatchQueue.global().async {
sleep(UInt32(1))
print("\(i)")
sem.signal()
}
}
for _ in 0..<10 {
sem.wait()
}
DispatchQueue.main.async {
print("开始执行任务A")
}
方法三: 简单粗暴的bool数组,不推荐, 高并发容易崩溃
self.arr = [[NSMutableArray alloc] init];
for (int i=0; i<10; i++)
{
[self.arr addObject: [NSNumber numberWithBool:false]];
}
for (int i=0; i<10; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(i);
self.arr[i] = [[NSNumber alloc] initWithBool:true];
if (![self.arr containsObject:[NSNumber numberWithBool:false]]) {
NSLog(@"开始执行任务A");
}
});
}
如果将sleep(i)改成sleep(1)就会发现崩溃了,原因是因为在遍历arr的时候对arr进行了修改。