NSThread
- 創(chuàng)建和啟動(dòng)線程的3個(gè)方法
1> 先創(chuàng)建伴嗡,后啟動(dòng)
// 創(chuàng)建
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download) object:nil];
// 設(shè)置線程的名字
thread.name = @"下載線程01";
// 設(shè)置線程的優(yōu)先級(jí)(取值 0.0 - 1.0)
thread.threadPriority = 0.5;
// 啟動(dòng)
[thread start];
-(void) download{
[self performSelectorOnMainThread:@selector(back:) withObject:@"back" waitUntilDone:NO];
}
-(void) back:(id)obj{
NSLog("%@",obj);
NSLog("%@,[NSThread currentThread]);
}
2> 創(chuàng)建完自動(dòng)啟動(dòng)
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:nil];
3> 隱式創(chuàng)建(自動(dòng)啟動(dòng))// NSObject開(kāi)啟線程
[self performSelectorInBackground:@selector(download:) withObject:nil];
// waitUntilDone:YES 表示當(dāng)@selector執(zhí)行完畢后后面的代碼才執(zhí)行硬猫。
[self performSelectorOnMainThread:@selector(download:) withObject:nil waitUntilDone:NO];
4> runloop
- Runloop是程序啟動(dòng)后建立的一個(gè)主運(yùn)行循環(huán),保證程序不退出,而且還負(fù)責(zé)監(jiān)聽(tīng)事件,如觸摸,定
時(shí)器、網(wǎng)絡(luò)請(qǐng)求完成登渣。 - 沒(méi)有事件時(shí),進(jìn)行休眠。
- 有事件時(shí),被喚醒,接收事件,找到最合適的處理對(duì)象。
- 主線程和子線程的運(yùn)行循環(huán):
1)主線程和子線程都有運(yùn)行循環(huán)
2)主線程的運(yùn)行循環(huán)是工作的 主線程中是有autoreleasepool的
3)使用GCD和NSOperation創(chuàng)建的線程會(huì)添加自動(dòng)釋放池
4)使用NSThread的線程不會(huì)自動(dòng)添加autoreleasepool
NSThread和NSObject如果在后臺(tái)創(chuàng)建了autorelease對(duì)象 "需要使用自動(dòng)釋放池 否則會(huì)出現(xiàn)內(nèi)存泄漏",所以前面的代碼要加上autoreleasepool
- 注意點(diǎn):線程任務(wù)一旦執(zhí)行完畢或者線程一旦強(qiáng)制退出始绍,不能再重新開(kāi)啟線程,只能重新創(chuàng)建線程话侄。