一道多线程面试题

题目如下:

- (void)viewDidLoad {
    [super viewDidLoad];

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"4");
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"5");
    });

    [self performSelector:@selector(test2)];
    [self performSelector:@selector(test3) withObject:nil afterDelay:0];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSLog(@"6");
    });
    [self test1];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)test1{
    NSLog(@"1");
}
- (void)test2{
    NSLog(@"2");
}
- (void)test3{
    NSLog(@"3");
}
求执行顺序:

分析:

   1、[self performSelector:@selector(test2)];和 [self test1];  都是在主线程中执行的所以 2 在1 前。
   2、然后   NSLog(@"6"); 是在异步线程中只要在2之后随便一个位置都可以(应该在1之后、视执行速度而定)

   3、分析 [self performSelector:@selector(test3) withObject:nil afterDelay:0]; 这个方法是异步方法,只能在主线程中调用故在2 1 之后
   4、4 和 5 都是需要获取主线程然后在主线程中执行。最快在输出 2 1 3 之后执行;最慢在输出2 1 3后的时间再加上一次runloop时间执行
   故顺序为 2 1 3 4 5 。6可以插入在2之后的任意位置。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值