zoukankan      html  css  js  c++  java
  • OC原理之多线程(一)

    对于如下的代码,打印结果是什么

    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            NSLog(@"1");
            [self performSelector:@selector(testhaha) withObject:nil afterDelay:.0];
            NSLog(@"3");
    });
    
    - (void)testhaha {
        NSLog(@"2");
    }

    运行之后打印如下:

    2021-02-23 23:14:10.384150+0800 KVOTest[17526:624011] 1
    2021-02-23 23:14:10.384456+0800 KVOTest[17526:624011] 3

    从打印结果来看,2并没有打印,究其原因是,performSelector:withObject:afterDelay:的本质是往Runloop中添加定时器,但是子线程中的runloop默认是没有启动的

    可通过如下的代码:

    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            NSLog(@"1");
            [self performSelector:@selector(testhaha) withObject:nil afterDelay:.0];
            [[NSRunLoop currentRunLoop] run];
            NSLog(@"3");
     });
    
    - (void)testhaha {
        NSLog(@"2");
    }

    或者直接放在主线程中执行:

    dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            NSLog(@"1");
            [self performSelector:@selector(testhaha) withObject:nil afterDelay:.0];
            [[NSRunLoop currentRunLoop] run];
            NSLog(@"3");
     });
    
    - (void)testhaha {
        NSLog(@"2");
    }
  • 相关阅读:
    LeetCode: 18. 4Sum
    LeetCode:15. 3Sum
    Leetcode:1. Two Sum
    tensorflow placeholder
    Tensorflow变量
    13.git的简单使用
    13.Django1.11.6文档
    12.python进程协程异步IO
    12.Flask-Restful
    12.Django思维导图
  • 原文地址:https://www.cnblogs.com/muzichenyu/p/14438910.html
Copyright © 2011-2022 走看看