一、建立和啟動線程簡單說明
一個nsthread對象就代表一條線程
建立、啟動線程
(1) 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];
線程的排程優先級:排程優先級的取值範圍是0.0 ~ 1.0,預設0.5,值越大,優先級越高
+ (double)threadpriority;
+ (bool)setthreadpriority:(double)p;
設定線程的名字
- (void)setname:(nsstring *)n;
- (nsstring *)name;
其他建立線程的方式
(2)建立線程後自動啟動線程 [nsthread detachnewthreadselector:@selector(run) totarget:self withobject:nil];
(3)隐式建立并啟動線程 [self performselectorinbackground:@selector(run) withobject:nil];
上述2種建立線程方式的優缺點
優點:簡單快捷
缺點:無法對線程進行更詳細的設定
二、代碼示例
1.使用古老的方式建立


實作效果:
列印結果:
2.使用nsthread建立線程


調用線程1,列印結果為:
調用線程2
調用線程3