主要概念
队列 dispatch_queue_t,队列名称在调试时辅助,无论什么队列和任务,线程的创建和回收不需要程序员操作,有队列负责。
串行队列:队列中的任务只会顺序执行(类似跑步)
dispatch_queue_t q = dispatch_queue_create(“....”, dispatch_queue_serial);
并行队列: 队列中的任务通常会并发执行(类似赛跑)
dispatch_queue_t q = dispatch_queue_create("......", dispatch_queue_concurrent);
全局队列:是系统开发的,直接拿过来(get)用就可以;与并行队列类似,但调试时,无法确认操作所在队列
dispatch_queue_t q = dispatch_get_global_queue(dispatch_queue_priority_default, 0);
主队列:每一个应用开发程序对应唯一一个主队列,直接get即可;在多线程开发中,使用主队列更新ui
dispatch_queue_t q = dispatch_get_main_queue();
操作
dispatch_async 异步操作,会并发执行,无法确定任务的执行顺序;
dispatch_sync 同步操作,会依次顺序执行,能够决定任务的执行顺序;
具体实现
//sync+串行队列 总结: 不开新的线程
- (IBAction)OnOneClick:(UIButton *)sender {
// 1.创建串行队列
dispatch_queue_t queue = dispatch_queue_create("com.itheima.queue", NULL);
// 2.添加任务到队列中 执行
dispatch_sync(queue, ^{
NSLog(@"----下载图片1-----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"----下载图片2-----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"----下载图片3-----%@", [NSThread currentThread]);
});
}
//async+串行队列 总结: 只开1个新线程
- (IBAction)OnTwoClick:(UIButton *)sender {
// 1.创建串行队列
dispatch_queue_t queue = dispatch_queue_create("com.itheima.queue", NULL);
// 2.添加任务到队列中 执行
dispatch_async(queue, ^{
NSLog(@"----下载图片1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----下载图片2-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----下载图片3-----%@", [NSThread currentThread]);
});
}
//sync+并行队列 总结: 不开新线程, 并发队列失去并发功能
- (IBAction)OnThreeClick:(UIButton *)sender {
//获取全局并行队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(queue, ^{
NSLog(@"----下载图片1-----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"----下载图片2-----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"----下载图片3-----%@", [NSThread currentThread]);
});
}
//async+并行队列 // 总结: 同时开3个新线程
- (IBAction)OnFourClick:(UIButton *)sender {
// 1.获得全局的并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 2.添加任务到队列中 执行
dispatch_async(queue, ^{
NSLog(@"----下载图片1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----下载图片2-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----下载图片3-----%@", [NSThread currentThread]);
});
}
//sync+主队列 通过sync函数将任务放入主队列,会导致主线程死锁
- (IBAction)OnFiveClick:(UIButton *)sender {
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_sync(queue, ^{ //死锁,UI线程卡死
NSLog(@"会死锁哦");
});
}
//async+主队列 不开起新线程
- (IBAction)OnSixClick:(UIButton *)sender {
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
NSLog(@"async+主队列");
});
}