線程異步處理后恤筛,主線程再處理
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"異步線程");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"異步主線程");
});
});
延時(shí)處理
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds*NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^{
NSLog(@"演示操作,主線程刷新");
});
判斷三個(gè)并發(fā)隊(duì)列執(zhí)行完畢的方法dispatch_group_notify
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
NSLog(@"0");
});
dispatch_group_async(group, queue, ^{
NSLog(@"1");
});
dispatch_group_async(group, queue, ^{
NSLog(@"2");
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"執(zhí)行over");
});
執(zhí)行某個(gè)方法多少次數(shù)后笔喉,主線程才執(zhí)行,dispatch_apply 遍歷數(shù)組這個(gè)方法雖然會(huì)開啟多個(gè)線程來遍歷這個(gè)數(shù)組观谦,但是在遍歷完成之前會(huì)阻塞主線程浩螺。
NSArray *array = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply([array count], queue, ^(size_t index) {
NSLog(@"%zu====%@",index,array[index]);
});
NSLog(@"阻塞");
計(jì)時(shí)器
dispatch_source_set_event_handler 計(jì)時(shí)器
__block int index = 0;
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
NSLog(@"------ index == %d -------",index);
index++;
if (index > 20) {
dispatch_source_cancel(timer);
}
});
dispatch_source_set_cancel_handler(timer, ^{
NSLog(@"取消");
});
dispatch_resume(timer);