NSThread 的創(chuàng)建與啟動(dòng)
[NSThread detachNewThreadSelector:@selector(testNSThread:) toTarget:self withObject:nil]; //第一種創(chuàng)建方法
[self performSelectorInBackground:@selector(testNSThread:) withObject:nil]; //第二種創(chuàng)建方法
NSThread* testThread= [[NSThread alloc] initWithTarget:self selector:@selector(testNSThread:) object:nil];//第三種創(chuàng)建方法
[testThread star];
區(qū)別:第一種調(diào)用方法會(huì)立即創(chuàng)建一個(gè)線程來(lái)執(zhí)行指定的任務(wù)澈蝙,第二種效果與第一種是一樣的,第三種調(diào)用方法直到我們手動(dòng) star 啟動(dòng)線程時(shí)才會(huì)去真正創(chuàng)建線程肌割。
線程的暫停、取消、停止
[NSThread sleepForTimeInterval:1.0];∥肚摹(暫停線程xx時(shí)間)
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];(暫停線程直到指定時(shí)間)
//NSThread的暫停會(huì)有阻塞當(dāng)前線程的效果
[testThread cancel];
//取消線程并不會(huì)馬上停止并退出線程澈缺,僅僅對(duì)線程做了一個(gè)標(biāo)記
[NSThread exit];
//停止方法會(huì)立即終止除主線程以外所有線程
獲取線程
[NSThread currentThread];//獲取當(dāng)前線程
[NSThread mainThread];//獲取主線程
線程間的通訊
**指定當(dāng)前線程執(zhí)行任務(wù)**
[self performSelector:@selector(testNSThread:)];
[self performSelector:@selector(testNSThread:) withObject:nil];
[self performSelector:@selector(testNSThread:) withObject:nil afterDelay:2.0];
**在子線程中指定主線程執(zhí)行任務(wù)(比如刷新UI)**
[self performSelectorOnMainThread:@selector(refreshUI) withObject:nil waitUntilDone:YES];
**在主線程中指定子線程執(zhí)行任務(wù)**
[self performSelector:@selector(testNSThread:) onThread:testThread withObject:nil waitUntilDone:YES];//指定名為 testThread 子線程執(zhí)行任務(wù)
[self performSelectorInBackground:@selector(testNSThread:) withObject:nil];//創(chuàng)建一個(gè)后臺(tái)線程執(zhí)行任務(wù)
```
####線程同步
*在多線程編程里面坪创,一些敏感數(shù)據(jù)不允許被多個(gè)線程同時(shí)訪問,此時(shí)就使用同步訪問技術(shù)姐赡,保證數(shù)據(jù)在任何時(shí)刻莱预,最多有一個(gè)線程訪問,以保證數(shù)據(jù)的完整性*
**iOS 實(shí)現(xiàn)線程加鎖有 NSLock 和 @synchronized 兩種方式**
```
_testArr = [NSMutableArray array];
_testlock = [[NSLock alloc] init];
NSThread* threadOne= [[NSThread alloc] initWithTarget:self selector:@selector(testLock :) object:nil];
[threadOne star];
NSThread* threadTwo= [[NSThread alloc] initWithTarget:self selector:@selector(testLock :) object:nil];
[threadTwo star];
** NSLog 實(shí)現(xiàn)同步鎖**
- (void)testLock:(id)obj {
[_testlock lock];
[_testArr addObject:obj];
[_testlock unlock];
}
** @synchronized 實(shí)現(xiàn)同步鎖**
- (void)testLock:(id)obj {
@synchronized (_testArr) {
[_testArr addObject:obj];
}
}
```
[詳細(xì)點(diǎn)擊這里](http://dwz.cn/5ylBI4)