NSThread建立多執行緒

2021-07-02 16:40:18 字數 1272 閱讀 2574

乙個nsthread的物件就代表乙個執行緒。

建立、啟動執行緒

nsthread *thread = [[nsthread alloc] initwithtarget:self selector:@selector(download) 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

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

[nsthread detachnewthreadselector:@selector(download:) totarget:self withobject:@"傳遞引數"];

隱式建立並啟動執行緒

[self performselectorinbackground:@selector(download:) withobject:@"傳遞引數"];

以上兩種建立執行緒的優缺點

優點:簡單快捷

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

// 睡眠5秒鐘

//    [nsthread sleepfortimeinterval:5];

// 3秒後的時間

//    nsdate *date = [nsdate datewithtimeintervalsincenow:3];

//    [nsthread sleepuntildate:date];

多執行緒 NSThread

我們想要載入網路上的一張 define url imag 然後初始化按鈕和乙個沒有的imageview 也可以再加乙個lable顯示資訊 主線程直接載入 self.imageview.image uiimage imagewithdata self loaddatawithurl url imag ...

iOS 多執行緒 NSThread

ibaction startthreadbuttonpressed uibutton sender 建立新的執行緒,執行緒的函式為 startthebackgroundjob.具體的 startthebackgroundjob 函式定義如下.void startthebackgroundjob 在第...

iOS 多執行緒 NSThread

nsthread thread nsthread alloc initwithtarget self selector selector run object nil thread start nsthread mainthread 獲得主線程 bool ismainthread 是否為主執行緒 b...