iOS 多线程面试题的输出类型考点

- (void)test {
    //并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    for (int i = 0; i < 1000; i++) {
        //超过数据线程总数,线程爆炸
        dispatch_async(queue, ^{
            self.name = [NSString stringWithFormat:@"abcdefghijk_%d",i];
        });
    }
    NSLog(@"name : %@",self.name);
}
//输出结果:crash,async 的异步线程,需要不断开辟线程。iOS的最大线程总数不到100个,所以1000个的时候,导致线程爆炸

- (void)test1 {
    NSLog(@"执行任务1");
    
    dispatch_queue_t queue = dispatch_queue_create("myqueu", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{ // 0
        NSLog(@"执行任务2");
        //相当于主线程调用了dispatch_sync(main)
        dispatch_sync(queue, ^{ // 1
            NSLog(@"执行任务3");
        });
        
        NSLog(@"执行任务4");
    });
    
    NSLog(@"执行任务5");
}
//输出:152 然后死锁了

- (void)test2
{
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    dispatch_async(queue, ^{
        NSLog(@"1");
        //没有加入runloop 不会执行这句话
        [self performSelector:@selector(test) withObject:nil afterDelay:.0];
        NSLog(@"3");
    });
}
//输出:1 3 不会执行test方法,原因afterDelay需要加入runloop才可以启动

你可能感兴趣的:(iOS 多线程面试题的输出类型考点)