回顧:(多線程的執(zhí)行原理 )同一時(shí)間, CPU只能運(yùn)行一條線程, 只有一條線程在工作, 多線程的原理其實(shí)是CPU在各個(gè)不同的線程之間不停地做切換, 因?yàn)閳?zhí)行切換的時(shí)間非忱牌拢快, 造成了同時(shí)執(zhí)行的假象.
為什么要用多線程 : 當(dāng)一個(gè)應(yīng)用程序只有單個(gè)主線程工作時(shí), 如果加載耗時(shí)任務(wù):(比如說 : 顯卡/音頻等等 I/O 設(shè)備), 線程會(huì)執(zhí)行的很慢, 這就會(huì)影響到用戶的體驗(yàn), 所以將任務(wù)分多個(gè)線程來執(zhí)行
iOS中多線程的實(shí)現(xiàn)
(方案1).pthread (跨平臺(tái)的C語言框架, 生命周期手動(dòng)管理, 不用)
(方案2).NSThread (OC, 生命周期手動(dòng)管理, 可直接操作線程對(duì)象)
#pragma mark (1) 直接創(chuàng)建一個(gè)帶方法的線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(longOperation:) object:@"thread"];
// 還需要手動(dòng)調(diào)用 start 方法來開啟線程
[thread start];
#pragma mark (2) 通過此方式無法拿到真的線程
[NSThread detachNewThreadSelector:(nonnull SEL) toTarget:(nonnull id) withObject:(nullable id)] ;
#pragma mark (3) 隱式創(chuàng)建線程來執(zhí)行方法
[self performSelector:(SEL)aSelector withObject:(id)arg];
NSThread 幾種線程操作:
(1).-(void)cancel : API : Changes the cancelled state of the receiver to indicate that it should exit. 翻譯 : 改變線程的狀態(tài)來標(biāo)識(shí)它應(yīng)該處于退出狀態(tài).
注意: 這種方式僅僅改變線程的狀態(tài), 并不一定就使得線程退出, 一般不這么用.
(2).[NSThread sleepForTimeInterval:(NSTimeInterval)] //休眠指定時(shí)長
[NSThread sleepUntilDate:(nonnull NSDate )] //休眠到指定的日期
以上2個(gè)方法會(huì)使得線程處于阻塞狀態(tài), 讓線程的循環(huán)對(duì)象源暫停循環(huán)
(3).[thread exit]* //終止當(dāng)前線程
Before exiting the thread, this method posts the [NSThreadWillExitNotification] with the thread being exited to the default notification center. Because notifications are delivered synchronously, all observers of [NSThreadWillExitNotification] are guaranteed to receive the notification before the thread exits.
Figure 3-1 shows the conceptual structure of a run loop and a variety of sources. The input sources deliver asynchronous events to the corresponding handlers and cause the [runUntilDate:]
method (called on the thread’s associated [NSRunLoop] object) to exit. Timer sources deliver events to their handler routines but do not cause the run loop to exit.
當(dāng)多個(gè)線程訪問同一變量的時(shí)候, 會(huì)造成什么現(xiàn)象? 如何解決?
互斥鎖的概念: 給訪問和操作這個(gè)單一變量的代碼, 加一把鎖.
#import "ViewController.h"
@interface ViewController ()
//票
@property(atomic,assign) int tickets;
//鎖
@property(nonatomic,strong) NSObject *obj;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tickets = 5;
self.obj = [[NSObject alloc] init];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//模擬賣票窗口
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
[thread1 start];
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
[thread2 start];
}
- (void)sellTickets {
while (YES) {
// @synchronized(obj)括號(hào)里填任意的對(duì)象(鎖), 這個(gè)對(duì)象(鎖)必須是同一個(gè)對(duì)象
@synchronized(self.obj) {
if(self.tickets > 0){
self.tickets = self.tickets - 1;
NSLog(@"余票%d %@",self.tickets,[NSThread currentThread]);
continue;
}
}
NSLog(@"沒有票了");
break;
}
}
@end
隱式創(chuàng)建子線程, 實(shí)現(xiàn)線程間通訊
在后臺(tái)線程下載圖像
[self performSelectorInBackground:@selector(downloadImage) withObject:nil];
在主線程設(shè)置圖像
[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
(方案3).GCD : 全稱是(§Grand Central Dispatch)
GCD 的優(yōu)點(diǎn): (1). (§純C語言, 提供了非常多強(qiáng)大的函數(shù)) 是蘋果公司為多核的并行運(yùn)算提出的解決方案, 旨在替代NSThread等線程技術(shù), 充分利用設(shè)備的CPU內(nèi)核
(2). GCD自動(dòng)管理線程的聲明周期 (創(chuàng)建線程, 調(diào)度任務(wù), 銷毀線程), 程序員只要告訴GCD要執(zhí)行什么任務(wù), 無需自己管理線程.
GCD使用的兩步: (1).定制任務(wù) (2).把任務(wù)添加到隊(duì)列中
GCD兩種調(diào)度任務(wù)的方式:
(1) "異步方式" :
dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@" 1 - %@",[NSThread currentThread]); });
(2) "同步方式" :
dispatch_sync(dispatch_get_global_queue(0, 0), ^{ NSLog(@" 2 - %@",[NSThread currentThread]); });
兩種方式的對(duì)比:
異步方式: <1>一定會(huì)開啟子線程執(zhí)行 block 任務(wù) <2>不用等待當(dāng)前語句執(zhí)行完畢,就可以執(zhí)行下一條語句 (就像下餃子一樣,一下子倒到鍋里)
同步方式: <1>不會(huì)開啟線程 <2>必須等待當(dāng)前的任務(wù)執(zhí)行完畢,才會(huì)執(zhí)行下一個(gè)任務(wù)
GCD的三種隊(duì)列:
(1) 串行隊(duì)列 : (自己創(chuàng)建/主隊(duì)列) 特點(diǎn) : 一次只能"調(diào)度"一個(gè)任務(wù)
(2) 并發(fā)隊(duì)列 : (自己創(chuàng)建/全局隊(duì)列) 特點(diǎn) : 一次可以"調(diào)度"多個(gè)任務(wù)
(3) 主隊(duì)列 : 一個(gè)特殊的串行隊(duì)列, 相當(dāng)于主線程 (在主線程空閑時(shí)才會(huì)調(diào)度隊(duì)列中的任務(wù)在主線程上執(zhí)行)
GCD進(jìn)行線程間測(cè)試
- (void)viewDidLoad {
[super viewDidLoad];
[self demo2];
}
- (void)demo2 {
dispatch_queue_t temp = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(temp, ^{
NSLog(@" 1--> %@",[NSThread currentThread]);
#warning 異步串行
dispatch_async(temp, ^{
NSLog(@" 2--> %@",[NSThread currentThread]);
});
NSLog(@"3333333333333");
});
#warning 同步并發(fā)
dispatch_sync(dispatch_get_global_queue(0, 0), ^{
NSLog(@" 3--> %@",[NSThread currentThread]);
dispatch_sync(temp, ^{
NSLog(@" 4--> %@",[NSThread currentThread]);
});
});
}
如圖所示的任務(wù)2是在任務(wù)1內(nèi)被添加到串行隊(duì)列中的, 由于是串行隊(duì)列, 所以必須在任務(wù)1之后才執(zhí)行, 所以先打印"333333",然后打印"3" 或"2", 任務(wù)2和任務(wù)3的順序是不固定的, 但是經(jīng)過試驗(yàn)很多次發(fā)現(xiàn),任務(wù)3先執(zhí)行的概率大一些, 分析原因可能是主線程的優(yōu)先級(jí)更高, 任務(wù)四在串行隊(duì)列最末, 最后執(zhí)行.
GCD小錯(cuò)誤demo
串行同步方式導(dǎo)致死鎖
- (void)viewDidLoad {
[super viewDidLoad];
[self demo3];
}
-(void)demo3 {
dispatch_queue_t temp = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL);
dispatch_sync(temp, ^{
NSLog(@" 1--> %@",[NSThread currentThread]);
**warning 在當(dāng)前這個(gè)串行隊(duì)列中有兩個(gè)任務(wù),使用同步方式運(yùn)行會(huì)造成死鎖**
dispatch_sync(temp, ^{
NSLog(@" 2--> %@",[NSThread currentThread]);
});
NSLog(@"333");
});
}
問題的總結(jié) : 由于使用同步的方式來執(zhí)行串行隊(duì)列中的任務(wù), 導(dǎo)致了只能夠順序地執(zhí)行隊(duì)列里的任務(wù), 這時(shí)我們的隊(duì)列temp
中有兩個(gè)同步任務(wù), 而且是嵌套執(zhí)行的. 這時(shí)當(dāng)UI線程執(zhí)行到第二個(gè)同步任務(wù)時(shí), 就會(huì)等待第一個(gè)任務(wù)執(zhí)行完畢, 可是第二個(gè)任務(wù)是嵌套在第一個(gè)任務(wù)內(nèi)的, 因此造成了死鎖.
解決方案:
#warning 解決方案:將兩個(gè)任務(wù)中的任意一個(gè)的隊(duì)列改成其他的隊(duì)列
- (void)viewDidLoad {
[super viewDidLoad];
[self demo3];
}
-(void)demo3 {
dispatch_queue_t temp = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL);
dispatch_sync(dispatch_get_global_queue(0, 0), ^{
NSLog(@" 3--> %@",[NSThread currentThread]);
dispatch_sync(temp, ^{
NSLog(@" 4--> %@",[NSThread currentThread]);
});
});
}