一個(gè)正在運(yùn)行的應(yīng)用程序是一個(gè)進(jìn)程,一個(gè)進(jìn)程會默認(rèn)開啟一個(gè)主線程,但是在主線程中的操作是串行的,也就是當(dāng)有多個(gè)任務(wù)同時(shí)需要完成的時(shí)候,是按照順序一個(gè)個(gè)執(zhí)行。因此,為了提高效率,會在進(jìn)程中開啟多個(gè)線程,每個(gè)線程可以并行的執(zhí)行不同的任務(wù)。
此外,在ios程序中,處理用戶觸摸事件、刷新界面等操作是必須放到主線程中實(shí)現(xiàn)的,因此那些比較耗費(fèi)資源的,比如從網(wǎng)絡(luò)獲取數(shù)據(jù)、下載等操作可以放到子線程中,不然的話,很容易造成主線程阻塞,一旦主線程阻塞,就會出現(xiàn)卡頓的現(xiàn)象,影響用戶體驗(yàn)。
在ios中,使用多線程有三種方式,分別是:
(1)NSThread
NSThread是一種比較原始的使用線程的方式,它是輕量級的方式,與其他方式相比,能更直觀的控制線程對象。但是通過這種方式,需要管理線程的生命周期,如果想實(shí)現(xiàn)同步,還需要加鎖,會加大系統(tǒng)開銷。
(2)NSOperation和NSOperationQueue
NSOperation以面向?qū)ο蟮姆椒ǚ庋b了需要執(zhí)行的操作,然后將這個(gè)操作放到一個(gè)NSOperationQueue中異步執(zhí)行,不需要去管理線程與處理同步的問題。
(3)Grand Centeral Dispatch
簡稱GCD,是c語言的API。GCD中提供了一些新特性來實(shí)現(xiàn)設(shè)備多核的并行編程。
在本篇文章,我們先來講解一下NSThread的使用。
NSThread
NSThread是線程類,一個(gè)NSThread實(shí)例就代表是一個(gè)線程。
獲取主線程
代碼
NSThread *mainThread = [NSThread mainThread];
獲取當(dāng)前線程
代碼
NSThread *currentThread = [NSThread currentThread];
NSThread創(chuàng)建
(1)動(dòng)態(tài)方法:通過對象方法來創(chuàng)建線程,需要手動(dòng)開啟線程
代碼
//初始化線程NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(startThread:) object: @"ios"];thread1.name = @"thread1";//開啟線程[thread1 start];
通過開啟線程調(diào)用的方法
代碼
-(void)startThread:(NSString *)parm{ NSThread *currentThread = [NSThread currentThread]; for (int i=0; i<10; i++) { NSLog(@"參數(shù)為 %@, 當(dāng)前的線程為 %@, 線程的名字為 %@",parm,currentThread,currentThread.name); }}
(2)靜態(tài)方法:通過類方法開啟線程,系統(tǒng)自動(dòng)調(diào)用
代碼
[NSThread detachNewThreadSelector:@selector(startThread:) toTarget:self withObject:@"jredu"];
(3)隱式方法開啟線程
代碼
[self performSelectorInBackground:@selector(startThread:) withObject:@"apple"];
暫停當(dāng)前的線程
代碼
//方法一[NSThread sleepForTimeInterval:2]; //方法二NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];[NSThread sleepUntilDate:date];
在某個(gè)線程上執(zhí)行操作
(1)在指定線程執(zhí)行操作
代碼
[self performSelector:@selector(run) onThread:thread1 withObject:nil waitUntilDone:YES];
(2)在主線程執(zhí)行操作
代碼
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
(3)在當(dāng)前線程執(zhí)行操作
代碼
[self performSelector:@selector(run) withObject:nil];

新聞熱點(diǎn)
疑難解答
圖片精選