一、多線程N(yùn)SThread
- 1.多線程基礎(chǔ)知識
- 線程與進(jìn)程的關(guān)系
(1). 線程是CPU執(zhí)行任務(wù)的基本單位,一個進(jìn)程能有多個線程,但同時只能執(zhí)行一個任務(wù)
(2). 進(jìn)程就是運(yùn)行中的軟件,是動態(tài)的
(3). 一個操作系統(tǒng)可以對應(yīng)多個進(jìn)程,一個進(jìn)程可以有多條線程,但至少有一個線程
(4). 同一個進(jìn)程內(nèi)的線程共享進(jìn)程里的資源
(5). 進(jìn)程不能執(zhí)行任務(wù)
- 主線程
(1). 進(jìn)程一啟動就自動創(chuàng)建
(2). 顯示和刷新UI界面
(3). 處理UI事件 - 子線程
(1). 處理耗時的操作
(2). 子線程不能用來刷新UI - 2.NSThread開辟線程的兩種方式
(1)創(chuàng)建手動開啟方式
第三個參數(shù):就是方法選擇器選擇方法的參數(shù)
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread1:) object:@"thread1"];
開啟線程
[thread start];
(2)創(chuàng)建并自動開啟方式
[NSThreaddetachNewThreadSelector:@selector(threadAction:) toTarget:selfwithObject:@"thread3"];
常用屬性:
NSThread isMainThread 判斷當(dāng)前線程是否是主線程
NSThread isMultiThreaded 判斷當(dāng)前線程是否是多線程
[NSThread setThreadPriority:1.0]; 設(shè)置線程的優(yōu)先級(0-1)
[NSThread sleepForTimeInterval:2]; 讓線程休眠
-
3、一個示例,使用多線程加載一張圖片
步驟:
(1)創(chuàng)建一個UIImageView,并放在父視圖上
(2)創(chuàng)建一個子線程
(3)通過url獲取網(wǎng)絡(luò)圖片
(4)回到主線程
(5)在主線程更新UI首先宏定義圖片網(wǎng)址:#define kUrl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943" 定義全局變量:UIImageView *myView;
在這使用第二種方式自動開啟線程
[NSThread detachNewThreadSelector:@selector(threadAction:) toTarget:selfwithObject:@"thread3"];
初始化myView
myView = [[UIImageView alloc]initWithFrame:self.view.frame];
[self.viewaddSubview:myView];
- (void)threadAction:(NSString*)sender{
// 從網(wǎng)絡(luò)加載圖片將它轉(zhuǎn)化為data類型的數(shù)據(jù)
NSData*data = [NSDatadataWithContentsOfURL:[NSURLURLWithString:kUrl]];
UIImage *image = [UIImage imageWithData:data];
// waitUntilDone 設(shè)置為YES 意味著UI更新完才會去做其他操作回到主線程
[selfperformSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
}
- ( void)updateUI:(UIImage*)kimage{
myView.image= kimage;
NSLog(@"updateUI這個方法是所在的線程 %@",[NSThread currentThread]);
}
二、多線程N(yùn)SOperation 與 NSOperationQueue 搭配進(jìn)行多線程開發(fā)
1.NSInvocationOperation 和 NSOperationQueue 搭配進(jìn)行多線程開發(fā)
步驟:
1.創(chuàng)建視圖
2.創(chuàng)建線程
3.創(chuàng)建線程隊(duì)列
4.把線程放在線程隊(duì)列中
5.在子線程中加載網(wǎng)絡(luò)資源
6.回到主線程
7.在主線程更新UI-
一個代碼示例:
前期工作:宏定義
和全局變量#define kurl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943" @interface ViewController () { UIImageView*myImageView; UIImage*iamges; } @end1.創(chuàng)建視圖
myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
myImageView.backgroundColor = [UIColor cyanColor];
[self.viewaddSubview:myImageView];2、創(chuàng)建線程
NSInvocationOperation*invoOp = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(loadResource) object:nil];
3、創(chuàng)建線程隊(duì)列
NSOperationQueue*operaTionQu = [NSOperationQueuenew];
4、把線程操作放在線程隊(duì)列中
[operaTionQu addOperation:invoOp];
5、在子線程中加載網(wǎng)絡(luò)資源
- (void)loadResource{
NSData*data = [NSDatadataWithContentsOfURL:[NSURLURLWithString:kurl]];
iamges= [UIImageimageWithData:data];
6、回到主線程
[[NSOperationQueuemainQueue] addOperationWithBlock:^{
7、更新UI
myImageView.image = iamges;
}];
}
2.NSBlockOperation 和 NSOperationQueue搭配
一個代碼示例:
前期工作:宏定義和全局變量
#define kurl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943"
@interface TwoViewController ()
{
UIImageView *myImageView;
UIImage *images;
}
@end
1、創(chuàng)建視圖
myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
myImageView.backgroundColor = [UIColor cyanColor];
[self.viewaddSubview:myImageView];
2、創(chuàng)建一個線程
NSBlockOperation*blockOperation = [NSBlockOperationblockOperationWithBlock:^{
5、在子線程中加載網(wǎng)絡(luò)資源
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kurl]];
images = [UIImage imageWithData:data];
6、回到主線程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
7、 更新UI
myImageView.image = images;
}];
}];
3、創(chuàng)建線程隊(duì)列
NSOperationQueue*opQu = [NSOperationQueuenew];
作放進(jìn)線程隊(duì)列里
[opQu addOperation:blockOperation];
3.用自定義NSOperation的類與NSOperationQueue搭配
代碼示例:
新建類CustomOperation繼承于NSOperation
并導(dǎo)入框架#import <UIKit/UIKit.h>
CustomOperation.h文件
@property (nonatomic,retain) UIImageView *iamgeViews;
- (instancetype)initWith:(UIImageView*)imageView;
CustomOperation.m文件
宏定義:#define kurl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943"
- (instancetype)initWith:(UIImageView *)imageView{
self= [super init];
if(self) {
self.iamgeViews = imageView;
}
returnself;
}
- (void)main{
// 需要創(chuàng)建一個自動釋放池,因?yàn)樵谶@里無法訪問到主線程的自動釋放池
@autoreleasepool{
// 5、在子線程中加載網(wǎng)絡(luò)資源
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kurl]];
UIImage *image = [UIImage imageWithData:data];
// 6、回到主線程
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
// 7、更新UI
self.iamgeViews.image = image;
}];
}
}
在控制器里
1、創(chuàng)建視圖
myImageView= [[UIImageViewalloc]initWithFrame:CGRectMake(50, 250, 200, 200)];
myImageView.backgroundColor= [UIColorcyanColor];
[self.viewaddSubview:myImageView];
2、創(chuàng)建一個線程操作在類中重寫main方法
CustomOperation*cus = [[CustomOperationalloc]initWith:myImageView];
3、創(chuàng)建一個線程隊(duì)列
NSOperationQueue*opera = [NSOperationQueuenew];
4、把線程操作放到線程隊(duì)列中
[opera addOperation:cus];
三、多線程之GCD(推薦)
1.GCD基礎(chǔ)知識
- 1、什么是GCD
全稱是Grand Central Dispath 純C語言編寫,提供非常多且強(qiáng)大的函數(shù),是目前推薦的多線程開發(fā)方法,NSOperation便是基于GCD的封裝 - 2、GCD的優(yōu)勢
1.為多核的并行運(yùn)算提出了解決方案
2.GCD會自動利用更多的CPU內(nèi)核,比如 雙核,四核
3、GCD自動管理線程的生命周期(創(chuàng)建線程,調(diào)度任務(wù),銷毀線程)
4.程序員只需告訴GCD想要執(zhí)行什么任務(wù),不需要編寫任何線程管理代 - 3、GCD中的兩個核心概念
1.任務(wù):執(zhí)行什么操作
2.隊(duì)列:用來存放任務(wù) - 4、隊(duì)列可分為兩大類型
(1)串行隊(duì)列(Serial Dispatch Queue): 只能有一個線程,加入到隊(duì)列中的操作按添加順序依次執(zhí)行,一個任務(wù)執(zhí)行完畢后 才能執(zhí)行下一個任務(wù)
(2)并發(fā)隊(duì)列(Concurrent Dispatch Queue): 可以有多個線程,操作進(jìn)來之后他會將這些線程安排在可用的處理器上,同時保證先進(jìn)來的任務(wù)優(yōu)先處理
(3)還有一個特殊的隊(duì)列就是主隊(duì)列,主隊(duì)列中永遠(yuǎn)只有一個線程-主線程,用來執(zhí)行主線程的操作任務(wù) - 5、采用GCD做多線程,可抽象為兩步
1、找到隊(duì)列
2、在隊(duì)列中用同步或者異步的方式執(zhí)行任務(wù) - 6.執(zhí)行隊(duì)列中任務(wù)的兩種方式
(1)同步:只能在當(dāng)前線程執(zhí)行任務(wù),不具備開啟新線程的能力
(2)異步:可以在新的線程中執(zhí)行任務(wù),具備開啟新線程的能力 - 7、GCD創(chuàng)建的線程任務(wù)有四種方式
2、 GCD的幾種搭配方式(注意總結(jié)規(guī)律進(jìn)行記憶)
#pragma mark-----串行同步
dispatch_queue_tserialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(serialQueue, ^{
//
NSLog(@"%@",[NSThread currentThread]);
});
#pragma mark-----串行異步
dispatch_queue_tserialQueue1 = dispatch_queue_create("serialQueue1", DISPATCH_QUEUE_SERIAL);
dispatch_async(serialQueue1, ^{
NSLog(@"%@",[NSThread currentThread]);
});
#pragma mark----并行同步
dispatch_queue_tconcurrentQueue = dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_sync(concurrentQueue, ^{
NSLog(@"%@",[NSThread currentThread]);
});
#pragma mark----并行異步
dispatch_queue_tconcurrentQueue1 = dispatch_queue_create("concurrentQueue1", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrentQueue1, ^{
NSLog(@"%@",[NSThread currentThread]);
});
3、代碼實(shí)例:(此鏈接下是GCD示例的demo)
代碼示例:
#define kurl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943"
@interface MoreImageViewViewController ()
{
int imageTag;
UIImageView *myImageView;
dispatch_queue_t concurentQueue;
NSOperationQueue *operationQueues;
}
@end
在viewDidLoad中
- (void)viewDidLoad {
[super viewDidLoad];
imageTag = 100;
self.view.backgroundColor = [UIColor greenColor];
self.edgesForExtendedLayout = UIRectEdgeNone;
[self controlBtn];
/*
1、創(chuàng)建多個視圖
2、找到并行隊(duì)列
3、給這個并行隊(duì)列指定多個任務(wù)
4、在子線程加載網(wǎng)絡(luò)資源
5、回到主線程
6、更新UI
/
// 1、創(chuàng)建多個視圖
for (int i=0; i<3; i++) {
for (int j=0; j<2; j++) {
myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10+j200, 40+i*200, 190, 190)];
myImageView.backgroundColor = [UIColor orangeColor];
myImageView.tag = imageTag++;
[self.view addSubview:myImageView];
}
}
// 2、找到并行隊(duì)列
// 使用下面這個方式不按順序 因?yàn)橄旅孢@句找的是 系統(tǒng)的全局并行隊(duì)列
// concurentQueue = dispatch_get_global_queue(0, 0);
// 這個方式是按順序的 用的串行隊(duì)列
concurentQueue = dispatch_queue_create("concurentQueue", DISPATCH_QUEUE_SERIAL);
// 3、指定任務(wù)
for (int index=0; index<6; index++) {
dispatch_async(concurentQueue, ^{
[NSThread sleepForTimeInterval:1];
// 加載網(wǎng)絡(luò)資源
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kurl]];
UIImage *image = [UIImage imageWithData:data];
// 5、回到主線程
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_sync(mainQueue, ^{
// 6、刷新UI
for (int i=0; i<6; i++) {
UIImageView *iamgeView = [self.view viewWithTag:100+index];
iamgeView.image = image;
}
});
});
}
}
以下兩個方法是暫停和開啟線程的
- (void)controlBtn{
UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:@[@"暫停",@"開啟",]];
segment.frame = CGRectMake(50, 620, 300, 50);
segment.apportionsSegmentWidthsByContent = YES;
[self.view addSubview:segment];
[segment addTarget:self action:@selector(clickSegment:) forControlEvents:UIControlEventValueChanged];
}
- (void)clickSegment:(UISegmentedControl *)sender {
switch (sender.selectedSegmentIndex) {
case 0:{
// 暫停隊(duì)列
dispatch_suspend(concurentQueue);
}break;
case 1:{
// 恢復(fù)隊(duì)列
dispatch_resume(concurentQueue);
}break;
}
}