一. 創(chuàng)建線程的3種方法
1.alloc init
- (void)threadDemo1
{
// 這一句只是 分配內(nèi)存和初始化
??NSThread?*thread = [[NSThread?alloc]?initWithTarget:self?selector:@selector(demo1:)object:@"Thread"];
??// 這一句才是啟動(dòng)線程
??[thread?start];
}
2.detachNewThreadSelector
- (void)threadDemo2
{
??[NSThread?detachNewThreadSelector:@selector(demo1:)?toTarget:self?withObject:@"detach"];
}
3.performSelectorInBackground
- (void)threadDemo3
{
??[self?performSelectorInBackground:@selector(demo1:)?withObject:@"background"];
}
performSelectorInBackground 是NSObject的一個(gè)分類方法,意味著所有的NSObject都可以使用該方法,在其他線程執(zhí)行方法!
特點(diǎn):沒(méi)有thread 字眼,一旦指定,就會(huì)立即在后臺(tái)線程執(zhí)行selector 方法,是隱式的多線程方法,這種方法在使用時(shí)更加靈活!
例如:
一個(gè) Person 類繼承自NSObject,有個(gè)方法 loadData很耗時(shí),在viewController里實(shí)例化一個(gè)Person * P,可以這樣調(diào)用:
[PperformSelectorInBackground:@selector(loadData)withObject:nil];
二、NSLog是專門用來(lái)調(diào)試的,性能非常不好,在商業(yè)軟件中,要盡量去掉
三、
[NSThread currentThread],當(dāng)前線程對(duì)象,可以在所有的多線程技術(shù)中使用,通常用來(lái)判斷是否在主線程
輸出的信息中,關(guān)注 number
Number == 1 說(shuō)明是主線程
Number != 1 說(shuō)明不是主線程
四、線程狀態(tài)
//?線程狀態(tài)的demo
- (void)threadStatusDemo
{
??//?實(shí)例化線程對(duì)象(新建)
??NSThread?*t = [[NSThread?alloc]?initWithTarget:self?selector:@selector(threadStatus)object:nil];
??//?就緒
??[t?start];
}
- (void)threadStatus
{
??NSLog(@"睡會(huì)兒");
??//?阻塞
??// sleep?是類方法,會(huì)直接休眠當(dāng)前線程
??[NSThread?sleepForTimeInterval:2.0];
??for?(int?i =?0; i <?10; i++)
??{
????if?(i ==?4)
????{
??????NSLog(@"再睡會(huì)兒");
??????//?線程執(zhí)行中,滿足某個(gè)條件時(shí),再次休眠
??????[NSThread?sleepUntilDate:[NSDate?dateWithTimeIntervalSinceNow:2.0]];
????}
????NSLog(@"%@, %d", [NSThread?currentThread], i);
????if?(i ==?8)
????{
??????//?終止
??????//?一旦終止,后續(xù)所有的代碼都不會(huì)被執(zhí)行,注意:在終止線程之前,應(yīng)該注意釋放之前分配的對(duì)象,如果是ARC?開(kāi)發(fā),需要注意,清理C語(yǔ)言框架創(chuàng)建的對(duì)象,否則會(huì)出現(xiàn)內(nèi)存泄漏
??????[NSThread?exit];
????}
??}
??NSLog(@"能來(lái)嗎?");
}
五、線程屬性
name 、isMainThread
//?線程屬性
- (void)threadPropertyDemo
{
??NSThread?*t = [[NSThread?alloc]?initWithTarget:self?selector:@selector(threadProperty)object:nil];
??//?屬性1. name:在大的商業(yè)項(xiàng)目中,通常希望程序崩潰的時(shí)候,能夠獲取到程序準(zhǔn)確執(zhí)行所在的線程
??t.name?=?@"Thread A";
??[t?start];
}
- (void)threadProperty
{
??for?(int?i =?0; i <?2; i++)
??{
????NSLog(@"%@, %d", [NSThread?currentThread], i);
??}
??//?屬性2.?判斷是否是主線程
??if?(![NSThread?isMainThread])
??{
?????//?模擬崩潰
????NSMutableArray?*array = [NSMutableArray?array];
????[array?addObject:nil];
??}
}