iOS多線程之NSThread

1.建立和啓動線程
  •  一個NSThread對象就表明一條線程spa

  • 建立和啓動線程線程

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
// 線程一啓動,就會在線程thread中執行self的run方法
  • 主線程相關用法code

+ (NSThread *)mainThread; // 得到主線程
- (BOOL)isMainThread; // 是否爲主線程
+ (BOOL)isMainThread; // 是否爲主線程
  • 獲取當前線程orm

NSThread *current = [NSThread currentThread];
  • 線程調度的優先級對象

+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
- (double)threadPriority;
- (BOOL)setThreadPriority:(double)p;
調度優先級的取值範圍是0.0 ~ 1.0,默認0.5,值越大,優先級越高
  • 線程的名字get

- (void)setName:(NSString *)n;
- (NSString *)name;
2.其餘建立線程的方式
  • 建立線程後自動啓動線程it

[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
  • 隱式建立線程io

[self performSelectorInBackground:@selector(run) withObject:nil];
  • 上述兩種建立方式的優缺點form

優勢:簡單快捷class

缺點:沒法對線程進行更細緻的設置,沒有獲取到線程對象

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方法執行完再往下執行
相關文章
相關標籤/搜索