美文网首页
iOS多线程之NSThread

iOS多线程之NSThread

作者: d50486b28313 | 来源:发表于2017-05-06 15:28 被阅读0次

    NSThread的使用有三种方法:

    1. 使用alloc和start
        NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(runThread1) object:nil];
        [thread1 start];
    
    1. 使用detachNewThreadSelector
        [NSThread detachNewThreadSelector:@selector(runThread1) toTarget:self withObject:nil];
    
    1. 使用performSelectorInBackground
        [self performSelectorInBackground:@selector(runThread1) withObject:nil];
    

    获得当前线程:

    [NSThread currentThread];

    NSThread锁(使线程中的共享数据不会错乱,相互干扰):

    1. 使用@synchronized
        @synchronized (self) {
        }
    
    1. 使用NSCondition(lock和unlock必须成对出现)
        @property (nonatomic, strong) NSCondition *ticketCondition;
        self.ticketCondition = [[NSCondition alloc] init];
        [self.ticketCondition lock];
        ...
        [self.ticketCondition unlock];
    

    相关文章

      网友评论

          本文标题:iOS多线程之NSThread

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