iOS多线程之NSThread

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)