多线程——NSThread

创建和启动线程

  • 一个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];

// 线程的名字
- (void)setName:(NSString *)n;
- (NSString *)name;

其他创建线程方式:

// 创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

// 隐式创建并启动线程
[self performSelectorInBackground:@selector(run) withObject:nil];

/*
   * 上述2种创建线程方式的优缺点
   * 优点:简单快捷
   * 缺点:无法对线程进行更详细的设置
*/

 

posted @ 2016-10-09 12:53  iOS-eflying  阅读(209)  评论(0编辑  收藏  举报