NSThread
- 優(yōu)點(diǎn):輕量級(jí),更直觀的控制線程對(duì)象
- 缺點(diǎn):需要自己管理線程的生命周期董济,線程同步步清,線程枷鎖。這會(huì)導(dǎo)致一定的性能開銷虏肾。
代碼
一. 實(shí)例化
//初始化
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadRun1) object:nil];
//優(yōu)先級(jí) 0 - 1.0 1.0z最高
thread.threadPriority = 1.0;
//開始線程
[thread start];
或者使用類方法
//創(chuàng)建并開啟新線程
[NSThread detachNewThreadSelector:@selector(threadRun2) toTarget:self withObject:nil];
獲取當(dāng)前線程和主線程
//獲取當(dāng)前線程
NSThread *thread2 = [NSThread currentThread];
//獲取主線程
NSThread *main = [NSThread mainThread];
二. 延時(shí)執(zhí)行
//延時(shí)兩秒執(zhí)行
[NSThread sleepForTimeInterval:2];
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:date];
//延時(shí)執(zhí)行
[self performSelector:@selector(threadRun4) withObject:self afterDelay:2];
三. 線程通訊
//在指定線程執(zhí)行
[self performSelector:@selector(threadRun5) onThread:thread2 withObject:nil waitUntilDone:YES];
//在主線程執(zhí)行
[self performSelectorOnMainThread:@selector(threadRun6) withObject:nil waitUntilDone:YES];
//當(dāng)前線程執(zhí)行
[self performSelector:@selector(threadRun7) withObject:nil];
PS:第一次寫東西廓啊,主要用于自己的積累。