多线程&&Runloop

2018-05-24  本文已影响0人  抹不掉那伤1

2018-05-24

保持线程生命的方法

要让线程有不释放,只能让线程有执行不完的任务

NSThread * thread = [[NSThread alloc] initWithBlock:^{
        NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        while (!_finished) {
            [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.0001]];
        }
        NSLog(@"线程结束");
        
    }];
    
    [thread start];

只要上面的_finished变量为NO线程就不会死。

线程间的通讯

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSThread * thread = [[NSThread alloc] initWithBlock:^{
        
        NSLog(@"%@-----",[NSThread currentThread]);
        
        [[NSRunLoop currentRunLoop] run];
        
    }];
    
    [thread start];
    
    
    [self performSelector:@selector(otherMethod) onThread:thread withObject:nil waitUntilDone:NO];
    
}

-(void)otherMethod{
    NSLog(@"OtherMethod --- %@",[NSThread currentThread]);
}

上面的代码中如果没有[[NSRunLoop currentRunLoop] run];otherMethod方法是不会掉用的。

我的理解

performSelector: onThread: withObject: waitUntilDone:方法的作用是使对应线程的Runloop中的source产生一个事件。当Runloop查看source是否有事件产生时便会执行对应的方法。所以必须让对应线程的Runloop方法跑起来。

上一篇 下一篇

猜你喜欢

热点阅读