各种队列的执行结果
| 并发队列 | 串形队列 | 主队列 | |
|---|---|---|---|
| 同步(sync) | 1.没有开启新线程 2.串形执行 | 1.没有开启线程 2.串形执行 | 1.没有开启线程 2.串形执行 |
| 异步(async) | 1.没有开启新线程 2.并发执行任务 | 1.有开启新线程 2.串形执行任务 | 没有开启新线程 2.串形执行任务 |
规则:
只有异步,非主队列,才会开启新线程
死锁:
使用sync函数往当前串形队列添加任务,会卡住当前串形队列
主队列开启同步线程 1.队列的特点:排队,FIFO,先进先出 2.dispatch_sync需要马上当前线程完成 queue先进先出原理 包含(viewDidLoad,dispatch_sync两个任务队列)完成dispatch_sync需要viewDidLoad完成,dispatch_sync没法完成执行viewDidLoad就没法执行完
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t queue = dispatch_get_main_queue();//主队列都放在主线程
dispatch_sync(queue, ^{//同步
for (int i = 0; i < 110; i++) {
NSLog(@"执行任务1 %@",[NSThread currentThread]);
}
});
}
dispatch_queue_t queue = dispatch_queue_create( "myQueue", DISPATCH_QUEUE_SERIAL);//串行队列 队列的类型执行方式
dispatch_async(queue, ^{//任务1
NSLog(@"执行1");
dispatch_sync(queue, ^{//任务2
NSLog(@"这里也将产生死锁 任务1执行完才能执行");
});
NSLog(@"执行2");
});
###以下代码打印结果
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
NSLog(@"1");
[self performSelector:@selector(test) withObject:self afterDelay:0];//本质添加runloop里面添加定时器(字线程默认没有启动rumloop)
NSLog(@"3");
//开启runloop
//[[NSRunLoop currentRunLoop]addPort:[[NSPort alloc]init] forMode:NSDefaultRunLoopMode];
//[[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
});
}
- (void)test {
NSLog(@"2");
}
打印结果
2020-03-23 15:21:06.960451+0800 多线程[78991:1518734] 1
2020-03-23 15:21:06.961140+0800 多线程[78991:1518734] 3
- (void)test {
NSLog(@"2");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSThread *th = [[NSThread alloc]initWithBlock:^{
NSLog(@"1");
[[NSRunLoop currentRunLoop]addPort:[[NSPort alloc]init] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}];
[th start];
[self performSelector:@selector(test) onThread:th withObject:nil waitUntilDone:YES];
}
#先执行任务1 任务2 最后执行任务3:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//创建队列数祖
dispatch_group_t grounp = dispatch_group_create();
//创建并发队列
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
//创建异步任务
dispatch_group_async(grounp, queue, ^{
for (int i = 0; i < 5; i++) {
NSLog(@"任务1===%@",[NSThread currentThread]);
}
});
//等前面的任务执行完,会自动执行这个任务
dispatch_group_async(grounp, queue, ^{
for (int i = 0; i < 5; i++) {
NSLog(@"任务2===%@",[NSThread currentThread]);
}
});
dispatch_group_notify(grounp, queue, ^{
for (int i = 0; i < 5; i++) {
NSLog(@"任务3===%@",[NSThread currentThread]);
}
});
}