1.The main queue(主线程串行队列): 与主线程功能相同,提交至Main queue的任务会在主线程中执行
-(void)mainQueue{
dispatch_queue_t mainqueue = dispatch_get_main_queue();
dispatch_async(mainqueue, ^{
NSLog(@"主线程串行队列异步任务,在主线程中运行,不会死锁");
});
}
2.Global queue(全局并发队列): 全局并发队列由整个进程共享,有高、中(默认)、低、后台四个优先级别
-(void)globalQueue{
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
NSLog(@"1");
dispatch_async(globalQueue, ^{
sleep(2);
NSLog(@"2");
});
NSLog(@"3");
}
3.Custom queue (自定义队列): 可以为串行,也可以为并发
/**
自定义串行队列,同步时不可嵌套,会产生死锁。
*/
-(void)serialQueue{
dispatch_queue_t serialQueue = dispatch_queue_create("www", DISPATCH_QUEUE_SERIAL);
NSLog(@"1");
dispatch_async(serialQueue, ^{
NSLog(@"2");
dispatch_async(serialQueue, ^{
NSLog(@"3");
});
});
NSLog(@"4");
}
/**
自定义并发队列
*/
-(void)conCurrentQueue{
dispatch_queue_t conCurrenuQueue = dispatch_queue_create("www", DISPATCH_QUEUE_CONCURRENT);
NSLog(@"1");
dispatch_sync(conCurrenuQueue, ^{
NSLog(@"1");
dispatch_sync(conCurrenuQueue, ^{
NSLog(@"可以嵌套执行同步任务,不会产生死锁,异步任务都行");
});
});
NSLog(@"1");
}
4.Group queue (队列组):将多线程进行分组,最大的好处是可获知所有线程的完成情况,Group queue 可以通过调用dispatch_group_create()来获取,通过dispatch_group_notify,可以直接监听组里所有线程完成情况
-(void)groupQueue{
dispatch_queue_t conCurrentGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_group_t groupQueue = dispatch_group_create();
dispatch_group_async(groupQueue, conCurrentGlobalQueue, ^{
NSLog(@"1");
});
dispatch_group_async(groupQueue, conCurrentGlobalQueue, ^{
NSLog(@"2");
});
dispatch_group_notify(groupQueue, mainQueue, ^{
NSLog(@"执行完自线程以后,在主线程更新ui");
});
NSLog(@"4");
}
另外,dispatch_after延时添加到队列
-(void)afterQueue{
dispatch_time_t delayTime2 = dispatch_time(DISPATCH_TIME_NOW, 2*NSEC_PER_SEC);
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_after(delayTime2, mainQueue, ^{
NSLog(@"2s后");
});
NSLog(@"1");
}