美文网首页
2020-03-23 子线程中开启运行循环(五)

2020-03-23 子线程中开启运行循环(五)

作者: 幸福晓杰2016 | 来源:发表于2020-03-23 15:35 被阅读0次

    1.为什么子线程中运行循环是默认关闭的?
    首先一个子线程没事开启什么死循环啊?
    子线程用完就应该回收啊,释放内存,因为运行循环一直存在着干嘛?
    这不是浪费资源吗!!
    所以,它是默认关闭的。

    2.关闭的运行循环会影响子线程中那些方法的执行?
    定时器方法,不会执行,因为没有运行循环、
    perform方法,是带有延迟功能的方法,不会执行。
    对于perform方法可以看如下总结:

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        [self performSelectorInBackground:@selector(timerDemo) withObject:nil];
    }
    
    - (void)timerDemo
    {
        NSLog(@"begin");
        
    //    //方案一:
    //    // 1.创建定时器
    //    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fireDemo) userInfo:nil repeats:YES];
    //
    //    // 2.把定时器添加到当前子线程的运行循环(子线程的运行循环默认不开启)
    //    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    //
    //    // 3.手动开启子线程的运行循环 (这个是主线程的运行循环和子线程的运行循环唯一的不同点)
    //    // run : 一旦调用这个方法开启子线程的运行循环,就不会停止
    //    // 一旦开启运行循环,相当于就开启了死循环
    //    [[NSRunLoop currentRunLoop] run];
        
        // 方案二:
        // runUntilDate : 让子线程的运行循环,只执行指定的时间
    //     [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]];
        
        //方案三
    [self performSelector:@selector(TEST) withObject:nil afterDelay:0];//不开运行循环,方法永远不会被执行。
    //    [[NSRunLoop currentRunLoop] run];
        
    //    测试哪些方法没有运行循环时就不会执行
    [self performSelector:@selector(TEST)];//与运行循环无关,立即执行
    [self performSelector:@selector(TEST) withObject:nil];//与运行循环无关,立即执行
        //验证异步还是同步,是否会自锁?答案:异步调用,不会自锁。
        [self performSelectorInBackground:@selector(TEST) withObject:nil];
     
        NSLog(@"end");
    }
    

    相关文章

      网友评论

          本文标题:2020-03-23 子线程中开启运行循环(五)

          本文链接:https://www.haomeiwen.com/subject/hsqsyhtx.html