iOS多线程之NSThread

1.创建和启动线程
  •  一个NSThread对象就代表一条线程

  • 创建和启动线程

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
// 线程一启动,就会在线程thread中执行self的run方法
  • 主线程相关用法

+ (NSThread *)mainThread; // 获得主线程
- (BOOL)isMainThread; // 是否为主线程
+ (BOOL)isMainThread; // 是否为主线程
  • 获取当前线程

NSThread *current = [NSThread currentThread];
  • 线程调度的优先级

+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
- (double)threadPriority;
- (BOOL)setThreadPriority:(double)p;
调度优先级的取值范围是0.0 ~ 1.0,默认0.5,值越大,优先级越高
  • 线程的名字

- (void)setName:(NSString *)n;
- (NSString *)name;
2.其他创建线程的方式
  • 创建线程后自动启动线程

[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
  • 隐式创建线程

[self performSelectorInBackground:@selector(run) withObject:nil];
  • 上述两种创建方式的优缺点

优点:简单快捷

缺点:无法对线程进行更细致的设置,没有获取到线程对象

3.控制线程的状态
  • 启动线程

- (void)start; 
// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态
  • 阻塞(暂停)线程

+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
  • 强制停止线程

+ (void)exit;
// 进入死亡状态
注意:一旦线程停止(死亡)了,就不能再次开启任务
4.线程间通信的常见用法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
wait:是否等到aSelector方法执行完再往下执行


你可能感兴趣的:(iOS多线程之NSThread)