主線程,執(zhí)行UI刷新
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//執(zhí)行耗時的異步操作..
//................
//................
dispatch_async(dispatch_get_main_queue(), ^{
//回到主線程宫蛆,執(zhí)行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后執(zhí)行
});
dispatch_group_async隊列組實現(xiàn)多線程異步操作
1.調(diào)用隊列組的 dispatch_group_async先把任務(wù)放到隊列中全谤,然后將隊列放入隊列組中。
[或者使用隊列組的 dispatch_group_enter安皱、dispatch_group_leave組合 來實現(xiàn)dispatch_group_async]
2.當(dāng)所有任務(wù)都執(zhí)行完成之后调鬓,才執(zhí)行dispatch_group_notify block 中的任務(wù)。
#@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 {
// 打印當(dāng)前線程
NSLog(@"當(dāng)前線程---%@",[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, ^{
// 追加任務(wù)1111
for (int i = 0; i < 5; ++i) {
//模擬耗時操作
[NSThread sleepForTimeInterval:4];
//打印當(dāng)前線程
NSLog(@"1111---%@",[NSThread currentThread]);
}
});
dispatch_group_async(group, queue, ^{
// 追加任務(wù)2222
for (int i = 0; i < 6; ++i) {
//模擬耗時操作
[NSThread sleepForTimeInterval:4];
//打印當(dāng)前線程
NSLog(@"2222---%@",[NSThread currentThread]);
}
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//等前面的異步任務(wù)1酌伊、任務(wù)2都執(zhí)行完畢后腾窝,回到主線程執(zhí)行下邊任務(wù)
NSLog(@"任務(wù)1、任務(wù)2都執(zhí)行完畢");
for (int i = 0; i < 4; ++i) {
// 模擬耗時操作
[NSThread sleepForTimeInterval:2];
// 打印當(dāng)前線程
NSLog(@"3333---%@",[NSThread currentThread]);
}
NSLog(@"隊列組---end");
});
NSLog(@"代碼---end");
}