主线程,执行UI刷新
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//执行耗时的异步操作..
//................
//................
dispatch_async(dispatch_get_main_queue(), ^{
//回到主线程,执行UI刷新操作
//................
//................
});
});
延时操作
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//code to be executed after a specified delay code将在10后执行
});
dispatch_group_async队列组实现多线程异步操作
1.调用队列组的 dispatch_group_async先把任务放到队列中,然后将队列放入队列组中。
[或者使用队列组的 dispatch_group_enter、dispatch_group_leave组合 来实现dispatch_group_async]
2.当所有任务都执行完成之后,才执行dispatch_group_notify block 中的任务。
#@property(nonatomic, strong) dispatch_group_t group_t;
#@property(nonatomic, strong) dispatch_queue_t queue_t;
#pragma mark dispatch_group_async
- (void)gcd_dispatch_group {
// 打印当前线程
NSLog(@"当前线程---%@",[NSThread currentThread]);
NSLog(@"队列组---begin");
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(group, queue, ^{
// 追加任务1111
for (int i = 0; i < 5; ++i) {
//模拟耗时操作
[NSThread sleepForTimeInterval:4];
//打印当前线程
NSLog(@"1111---%@",[NSThread currentThread]);
}
});
dispatch_group_async(group, queue, ^{
// 追加任务2222
for (int i = 0; i < 6; ++i) {
//模拟耗时操作
[NSThread sleepForTimeInterval:4];
//打印当前线程
NSLog(@"2222---%@",[NSThread currentThread]);
}
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//等前面的异步任务1、任务2都执行完毕后,回到主线程执行下边任务
NSLog(@"任务1、任务2都执行完毕");
for (int i = 0; i < 4; ++i) {
// 模拟耗时操作
[NSThread sleepForTimeInterval:2];
// 打印当前线程
NSLog(@"3333---%@",[NSThread currentThread]);
}
NSLog(@"队列组---end");
});
NSLog(@"代码---end");
}