iOS多執行緒之NSThread

2021-06-27 23:36:01 字數 2359 閱讀 1518

ios多執行緒之nsthread

乙個nsthread物件就代表一條執行緒

1. 建立,啟動執行緒

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

[thread start];

主線程相關用法

+ (nsthread *)mainthread; // 獲得主線程

- (bool)ismainthread; // 是否為主執行緒

+ (bool)ismainthread; // 是否為主執行緒

2.nsthread基本屬性

獲得當前執行緒

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 *)name;

- (nsstring *)name;

3. nsthread 建立執行緒的其他方式

// 建立執行緒後自動啟動執行緒

[nsthread detachnewthreadselector:@selector(run) totarget:self withobject:nil];

// 隱式建立並啟動執行緒

[self performselectorinbackground:@selector(run) withobject:nil];

上述2種建立執行緒方式的優缺點

優點:簡單快捷

缺點:無法對執行緒進行更詳細的設定

4 . 執行緒的5種狀態

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

[thread start];

n啟動執行緒

- (void)start;

// 進入就緒狀態 ->執行狀態。當執行緒任務執行完畢,自動進入死亡狀態

阻塞(暫停)執行緒

+ (void)sleepuntildate:(nsdate*)date;

+ (void)sleepfortimeinterval:(nstimeinterval)ti;

// 進入阻塞狀態

強制停止執行緒

+ (void)exit;

// 進入死亡狀態

注意:一旦執行緒停止(死亡)了,就不能再次開啟任務

5. n 互斥鎖使用格式

@synchronized(鎖物件)

// 初始化鎖

nslock *lock = [[nslock alloc] init];

// 加鎖

[lock lock];

// 解鎖

[lock unlock];

注意:鎖定1份**只用1把鎖,用多把鎖是無效的

互斥鎖的優缺點

優點:能有效防止因多執行緒搶奪資源造成的資料安全問題

缺點:需要消耗大量的cpu資源

互斥鎖的使用前提:多條執行緒搶奪同一塊資源

執行緒同步的意思是:多條執行緒按順序地執行任務

互斥鎖,就是使用了執行緒同步技術

//5.

執行緒間通訊

什麼叫做執行緒間通訊在1

個程序中,執行緒往往不是孤立存在的,多個執行緒之間需要經常進行通訊

執行緒間通訊的體現

1個執行緒傳遞資料給另

1個執行緒在1

個執行緒中執行完特定任務後,轉到另

1個執行緒繼續執行任務

執行緒間通訊常用方法- (void)performselectoronmainthread:(sel)aselector withobject:(id)arg waituntildone:(bool)wait;

- (void)performselector:(sel)aselector onthread:(nsthread *)thr withobject:(id)arg waituntildone:(bool)wait;

例項1:- (ibaction)btn:(uibutton *)sender - (void)run}// @synchronized 加鎖測試** - (void)locktestelse } }}

iOS多執行緒之NSThread

1.建立和啟動執行緒 nsthread thread nsthread alloc initwithtarget self selector selector run object nil thread start nsthread mainthread 獲得主線程 bool ismainthrea...

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 建立執行...