iOS多執行緒之NSThread

2021-07-11 22:08:10 字數 1370 閱讀 8529

1.建立和啟動執行緒

nsthread *thread = [[nsthread alloc] initwithtarget:self selector:@selector(run) object:nil];

[thread start];

+ (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

ios多執行緒之nsthread 乙個nsthread物件就代表一條執行緒 1.建立,啟動執行緒 nsthread thread nsthread alloc initwithtarget self selector selector run object nil thread start 主線程相...

ios多執行緒之NSThread總結

因為不常用,所以nsthread需要掌握的沒有多少,會這些就夠了 1.建立方式 1 建立後啟動 nsthread thread nsthread alloc initwithtarget self selector selector download object 先建立,後啟動 thread st...

多執行緒之NSThread

nsthread thread nsthread alloc initwithtarget self selector selector run object nil 啟動執行緒 執行完畢會自動銷毀執行緒 thread start 主動銷毀執行緒 還未執行完畢就退出 thread exit 建立執行...