多線程----NSThread的使用、數(shù)據(jù)安全和通信

姓名:謝艾芳? ? 學(xué)號(hào):16040410073

轉(zhuǎn)自http://www.lxweimin.com/p/d1f15dc6e8c1

〖嵌牛導(dǎo)讀〗今天看了一天小碼哥的視頻,重新理解了一下多線程中的NSThread。希望把自己學(xué)到的和理解的能夠分享給大家。

〖嵌牛鼻子〗NSThread的使用、數(shù)據(jù)安全和通信

〖嵌牛提問(wèn)〗如何快速了解NSThread的使用、數(shù)據(jù)安全和通信?

〖嵌牛正文〗

NSThread的使用方法

當(dāng)線程的 number == 1 的時(shí)候說(shuō)明該線程是主線程,反之為子線程

? ? // 獲取主線程

? ? NSThread * mainThread = [NSThread mainThread];

? ? NSLog(@"主線程---%zd",mainThread);

? ?

? ? // 獲取當(dāng)前線程

? ? NSThread * currentThread = [NSThread currentThread];

? ? NSLog(@"子線程---%zd",currentThread);

NSThread的三種創(chuàng)建方法

alloc init? 創(chuàng)建線程,需要手動(dòng)啟動(dòng)線程

? ? // 1.創(chuàng)建線程

? ? NSThread * threadA = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"ABC"];

? ?

? ? // 設(shè)置名稱(chēng)

? ? threadA.name = @"子線程A";

? ? // 設(shè)置線程優(yōu)先級(jí)? 取值范圍 0.0 ~ 1.0 之間 最高1.0? 默認(rèn)優(yōu)先級(jí)是0.5

? ? threadA.threadPriority = 0.1;

? ? // 2.執(zhí)行線程

? ? [threadA start];

分離子線程 自動(dòng)啟動(dòng)線程

[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分離子線程"];

開(kāi)啟后臺(tái)線程

[self performSelectorInBackground:@selector(run:) withObject:@"開(kāi)啟后臺(tái)線程"];

執(zhí)行方法

- (void) run: (NSString *) param{

? ? NSLog(@"--------run---------%@---------%@",[NSThread currentThread],param);

}

阻塞線程方法

// 阻塞線程 阻塞時(shí)間完成后才會(huì)釋放線程

? ? // 方法1.

//? ? [NSThread sleepForTimeInterval:2.0];

? ? // 方法2.

? ? [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]];

? ?

? ? NSLog(@"end-----");

強(qiáng)制退出線程方法

- (void) task{

? ? for(NSInteger i = 0; i<100; i++){

? ? ? ? NSLog(@"%zd--------%@",i,[NSThread currentThread]);

? ? ? ?

? ? ? ? if(i == 20){

? ? ? ? ? ? // 強(qiáng)制退出線程

? ? ? ? ? ? [NSThread exit];

? ? ? ? ? ? break;

? ? ? ? }

? ? }

}

生命周期

NSThread的生命周期:當(dāng)線程執(zhí)行完成后會(huì)自動(dòng)釋放

NSThread的線程安全

互斥鎖

@synchronized (<#token#>) {

? ? ? ? <#statements#>

? ? }

互斥鎖優(yōu)缺點(diǎn)

優(yōu)點(diǎn):能有效防止因多線程搶奪資源造成的數(shù)據(jù)安全問(wèn)題

缺點(diǎn):需要消耗大量的CPU資源

使用互斥鎖的前提:多線程搶奪同一塊資源

相關(guān)專(zhuān)業(yè)術(shù)語(yǔ):線程同步

線程同步:多條線程在同一條線上執(zhí)行(按順序的執(zhí)行任務(wù))

我們模擬了三個(gè)售票員同時(shí)出售同100張機(jī)票,方法效果如下

設(shè)置變量

/** 售票員A */

@property (nonatomic, strong) NSThread * threadA;

/** 售票員B */

@property (nonatomic, strong) NSThread * threadB;

/** 售票員C */

@property (nonatomic, strong) NSThread * threadC;

/** 總票數(shù) */

@property (nonatomic, assign) NSInteger totalCount;

創(chuàng)建并執(zhí)行線程

? ? // 設(shè)置總票數(shù)

? ? self.totalCount = 100;

? ?

? ? // 創(chuàng)建線程

? ? self.threadA = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

? ? self.threadB = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

? ? self.threadC = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

? ?

? ? self.threadA.name = @"售票員A";

? ? self.threadB.name = @"售票員B";

? ? self.threadC.name = @"售票員C";

? ?

? ? // 執(zhí)行線程

? ? [self.threadA start];

? ? [self.threadB start];

? ? [self.threadC start];

執(zhí)行方法

如果沒(méi)有加互斥鎖的話會(huì)導(dǎo)致同一張票被三個(gè)售票員同時(shí)售出,這種情況我們當(dāng)然是不允許的

- (void) saleTicket{

? ?

? ? while (1) {

? ? ? ? // 鎖:必須是全局唯一的 一般使用 self

? ? ? ? // 1.注意加鎖位置

? ? ? ? // 2.注意加鎖的前提條件,多線程共享一塊資源

? ? ? ? // 3.注意加鎖是需要代價(jià)的,需要耗費(fèi)性能和時(shí)間

? ? ? ? // 4.加鎖的結(jié)果:線程同步? 當(dāng)線程A執(zhí)行的時(shí)候進(jìn)行加鎖 線程B在外等著線程A結(jié)束 鎖開(kāi)了執(zhí)行線程B

? ? ? ? @synchronized (self) {

? ? ? ? ? ? NSInteger count = self.totalCount;

? ? ? ? ? ?

? ? ? ? ? ? if(count > 0){

? ? ? ? ? ? ? ? // 耗時(shí)操作

? ? ? ? ? ? ? ? for(NSInteger i = 0; i<100000; i++){

? ? ? ? ? ? ? ? ? ?

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? self.totalCount = count - 1;

? ? ? ? ? ? ? ?

? ? ? ? ? ? ? ? NSLog(@"%@賣(mài)出一張票,還剩%zd張票",[NSThread currentThread].name,self.totalCount);

? ? ? ? ? ? }else{

? ? ? ? ? ? ? ? NSLog(@"票已經(jīng)賣(mài)完");

? ? ? ? ? ? ? ? break;

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ?

}

NSThread線程間的通信

當(dāng)子線程任務(wù)執(zhí)行完成之后如何返回值給主線程,再由主線程去刷新UI,下面我們由在網(wǎng)上下載一張圖片為栗子

線程間通信的三種方法

/**

? ? * 參數(shù)1. 調(diào)用方法

? ? ? 參數(shù)2. 方法傳遞值

? ? ? 參數(shù)3. 是否完成該方法后執(zhí)行下一步

? ? */

1.直接回到主線程

? ? // 方法1.

? ? [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];

2.回到指定NSThread線程

? ? // 方法2.

? ? [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];

3.省去顯示圖片函數(shù),直接在方法中實(shí)現(xiàn)

? ? // 方法3.

? ? [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];

注:方法3.是因?yàn)?UIImageView 繼承的最底層也是NSObject,而方法

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;

都是繼承NSObject,所以可以直接通過(guò) UIImageView 去調(diào)用方法,從而設(shè)置 UIImageView 的 image --> setImage:

創(chuàng)建線程

? ? NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@selector(download) object:nil];

? ?

? ? [thread start];

下載方法

- (void) download{

? ?

? ? // 1.獲取圖片rul

? ? NSURL * url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502704595&di=77a802f956215c509727a13dc7176b7a&imgtype=jpg&er=1&src=http%3A%2F%2Fatt.bbs.duowan.com%2Fforum%2F201306%2F08%2F220236m63ppvbxbevgrbrg.jpg"];

? ?

? ? // 2.根據(jù)url下載圖片二進(jìn)制數(shù)據(jù)到本地

? ? NSData * imageData = [NSData dataWithContentsOfURL:url];

? ?

? ? // 3.轉(zhuǎn)換圖片格式

? ? UIImage * image = [UIImage imageWithData:imageData];

? ?

? ? NSLog(@"download---%@",[NSThread currentThread]);

? ?

? ? // 4.回到主線程顯示UI

? ?

? ? /**

? ? * 參數(shù)1. 調(diào)用方法

? ? ? 參數(shù)2. 方法傳遞值

? ? ? 參數(shù)3. 是否完成該方法后執(zhí)行下一步

? ? */

? ?

? ? // 方法1.

//? ? [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];

? ? // 方法2.

//? ? [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];

? ? // 方法3.

? ? [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];

? ?

? ? NSLog(@"----end----");

}

顯示圖片方法

- (void) showImage: (UIImage *) image{

? ? self.imageView.image = image;

? ? NSLog(@"showImage---%@",[NSThread currentThread]);

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,182評(píng)論 6 543
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,489評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 178,290評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 63,776評(píng)論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,510評(píng)論 6 412
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 55,866評(píng)論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,860評(píng)論 3 447
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 43,036評(píng)論 0 290
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,585評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,331評(píng)論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,536評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,058評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,754評(píng)論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 35,154評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 36,469評(píng)論 1 295
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,273評(píng)論 3 399
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,505評(píng)論 2 379

推薦閱讀更多精彩內(nèi)容