1.獲取主線程方法:
NSThread *mainT = [NSThread mainThread];
NSLog(@"主線程:%@",mainT);
顯示結(jié)果:{name = (null),num = 1}
請(qǐng)記?。簄um = 1,才是主線程。num 相當(dāng)于線程的ID。
2.獲取當(dāng)前線程方法:
NSThread *currentT = {NSThread currentThread];
3.創(chuàng)建線程:
使用方法:- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
(1)創(chuàng)建方法:NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(runThread:)object:@"run"];
[threadstart]; //開啟線程
-(void)runThread:(NSString *)string{
NSThread *currentT = [NSThreadcurrentThread]; //當(dāng)前線程
NSLog(@"執(zhí)行runThread:方法,參數(shù)%@,當(dāng)前線程:%@",string,currentT); //打印當(dāng)前線程參數(shù)
}
結(jié)果:執(zhí)行runThread:方法,參數(shù)run,當(dāng)前線程{name = (null),num = 3}
num值為3,不是主線程,主線程num值為1.
(2)+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;靜態(tài)方法獲取線程
[NSThreaddetachNewThreadSelector:@selector(runThread:)toTarget:selfwithObject:@"run"];調(diào)用方法(啟動(dòng)一個(gè)新的線程,調(diào)用self的runThread:方法,以run為參數(shù))
(3)[selfperformSelectorInBackground:@selector(runThread:)withObject:@"run"];隱式創(chuàng)建線程
4.暫停當(dāng)前線程:
(1)[NSThreadsleepForTimeInterval:5]; //快捷方法暫停5秒
(2)NSDate *date = [NSDatedateWithTimeInterval:5sinceDate:[NSDatedate]];
[NSThreadsleepUntilDate:date]; //另一種方法暫停5秒
(1)在主線程上的執(zhí)行操作:
[selfperformSelectorOnMainThread:@selector(runThread:)withObject:nilwaitUntilDone:YES]; //在主線程上調(diào)用 runThread:方法
(2)在當(dāng)前線程執(zhí)行操作:[selfperformSelector:@selector(runThread:)withObject:nil]; //在當(dāng)前線程調(diào)用runThread:方法
(3)在指定線程執(zhí)行操作:
[self performSelector:@selector(runThread:) onThread:myThread withObject:nil waitUntilDone:YES]; //在myThread線程上調(diào)用 runThread:方法 YES :runThread:方法執(zhí)行完畢才會(huì)繼續(xù)往下執(zhí)行其他代碼
6.Thread線程更直觀控制線程對(duì)象,需要管理線程的生命周期,線程同步。線程同步對(duì)數(shù)據(jù)的加鎖會(huì)占用系統(tǒng)一定的內(nèi)存。
聯(lián)系客服