多線程——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種建立線程方式的優缺點
   * 優勢:簡單快捷
   * 缺點:沒法對線程進行更詳細的設置
*/
相關文章
相關標籤/搜索