多線程GCD geekband

GCD
Grand Central Dispatch

GCD中也有一個類似于NSOperationQueue的隊列,GCD統一管理整個隊列中的任務。但是GCD中的隊列分為并行隊列和串行隊列兩類:

串行隊列:只有一個線程,加入到隊列中的操作按添加順序依次執行。
串行隊列:有多個線程,操作進來之后它會將這些隊列安排在可用的處理器上,同時保證先進來的任務優先處理。

GCD中有2個用來執行任務的函數
只是根據隊列的性質,分為<1>串行隊列:用戶隊列、主線程隊列 <2>并行隊列.
說明:把右邊的參數(任務)提交給左邊的參數(隊列)進行執行。

 (1)用串行隊列的方式執行任務 dispatch_sync(dispatch_queue_t queue, dispatch_block_t block);

參數說明:

queue:隊列

block:任務

同步(dispatch_sync)、異步方式(dispatch_async). 配合串行隊列和并行隊列使用.

效果顯示.
異步串行


如果圖掛了 點擊超鏈接

異步并行


如果圖掛了 點擊超鏈接
同步

如果圖掛了 點擊超鏈接
我相信這里gif的展示令你更深刻認識到GCD.
其他任務執行方法


貼上案例

#import "ViewController.h"

@interface ViewController ()
@property (strong , nonatomic) NSMutableArray *imageView;
@property  (strong,nonatomic)   NSArray *imageNames;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//數組
NSString *Photo1 =[NSString stringWithFormat:@"http://news.mydrivers.com/img/20130518/3fed7f3e8ab848e284bb2238320cbd93.jpg"];
NSString *Photo2 =[NSString stringWithFormat:@"http://image.tianjimedia.com/uploadImages/2013/237/015W189B5F99_B75.JPG"];
NSString *Photo3 =[NSString stringWithFormat:@"http://pic.3h3.com/up/2014-6/20146614141118561372.jpg"];
NSString *Photo4 =[NSString stringWithFormat:@"http://www.3dmgame.com/uploads/allimg/130518/154_130518143149_1.jpg"];
NSString *Photo5 =[NSString stringWithFormat:@"http://b.hiphotos.baidu.com/zhidao/pic/item/cdbf6c81800a19d8a50020aa31fa828ba61e4619.jpg"];
NSString *Photo6 =[NSString stringWithFormat:@"http://img8.zol.com.cn/bbs/upload/23416/23415166.jpg"];
self.imageNames =[NSArray arrayWithObjects:
                 Photo1,Photo2,Photo3, Photo4,Photo5,Photo6,nil];

[self loadScrollViewWithButton];

}




-(void)loadimageViews{
//ImageView
_imageView=[NSMutableArray array];
for (int i = 0 ; i <6 ;  i++) {
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5 +(self.view.bounds.size.width/2 )*(i/3),(self.view.bounds.size.height/3 -25)*(i%3), self.view.bounds.size.width/2-10, self.view.bounds.size.width/2-10)];
    imageView.backgroundColor = [UIColor redColor];
    [self.view addSubview:imageView];
    [_imageView addObject:imageView];
    
}
}
-(void)loadScrollViewWithButton{
UIScrollView *scrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height -100, self.view.bounds.size.width, 40)];
scrollView.backgroundColor = [UIColor lightGrayColor];    scrollView.alpha = 0.6;
scrollView.contentSize = CGSizeMake(1000, 0);
[self.view addSubview:scrollView];

UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 1000, 60)];
lable.text = @"scrollView測試滾動,加載時滾動條體驗.圖片加載是否在主線程中";
[scrollView addSubview:lable];
//串行隊列
UIButton *TandemQueueButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
TandemQueueButton.frame=CGRectMake(0, self.view.bounds.size.height -60, 100,60);
[TandemQueueButton setTitle:@"異步串行隊列" forState:UIControlStateNormal];
TandemQueueButton.backgroundColor =[UIColor grayColor];
TandemQueueButton.alpha = 0.8;
[TandemQueueButton addTarget:self action:@selector(loadAsyncTandemQueue) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:TandemQueueButton];

//異步串行隊列
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(110, self.view.bounds.size.height -60, 100,60);
[button setTitle:@"異步并行隊列" forState:UIControlStateNormal];
button.backgroundColor =[UIColor grayColor];
button.alpha = 0.8;

[button addTarget:self action:@selector(loadAsyncParallelQueue) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

[TandemQueueButton addTarget:self action:@selector(loadAsyncTandemQueue) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:TandemQueueButton];

//同步隊列
UIButton *SynchronousButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
SynchronousButton.frame=CGRectMake(220, self.view.bounds.size.height -60, 100,60);
[SynchronousButton setTitle:@"同步隊列" forState:UIControlStateNormal];
SynchronousButton.backgroundColor =[UIColor grayColor];
SynchronousButton.alpha = 0.8;
[SynchronousButton addTarget:self action:@selector(loadsyncParallelQueue) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:SynchronousButton];

//計事件隊列
UIButton *timeButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
timeButton.frame=CGRectMake(330, self.view.bounds.size.height -60, 100,60);
[timeButton setTitle:@"延遲" forState:UIControlStateNormal];
timeButton.backgroundColor =[UIColor grayColor];
timeButton.alpha = 0.8;
[timeButton addTarget:self action:@selector(loadTimeQueue) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:timeButton];

}

#pragma mark 將圖片顯示到界面
-(void)updateImageWithData:(NSData *)data andIndex:(int )index{
UIImage *image=[UIImage imageWithData:data];
UIImageView *imageView= _imageView[index];
imageView.image=image;
}

#pragma mark 請求圖片數據
-(NSData *)requestData:(int)index{
NSURL *url=[NSURL URLWithString:_imageNames[index]];
NSData *data=[NSData dataWithContentsOfURL:url];
return data;
}
//圖片加載
-(void)loadImage:(NSNumber *)index{
int i = (int)[index integerValue];
NSData * data = [self requestData:i];
dispatch_queue_t mainQue = dispatch_get_main_queue()    ;



//為什么要用async?
//async 在主線程中  創建了一個異步線程 加入  全局并發隊列,async 不會等待block 執行完成,立即返回

// 1,async 立即返回, viewDidLoad 執行完畢,及主線程執行完畢。
//2,同時,全局并發隊列立即執行異步 block , 打印 1, 當執行到 sync 它會等待 block 執行完成才返回, 及等待
//dispatch_get_main_queue() 隊列中的 mianThread 執行完成, 然后才開始調用block 。

//體現一下卡頓  sync的卡頓.  他會在在updateImageWithData 卡頓了.因為沒有返回;
//    dispatch_async(mainQue, ^{
//        [self updateImageWithData:data andIndex:i];
//    });

dispatch_async(mainQue, ^{
    [self updateImageWithData:data andIndex:i];
});
}
//清除子view
-(void)cleanimage{
[_imageView makeObjectsPerformSelector:@selector(removeFromSuperview)];
}

//異步串行隊列意思是一張張按順序圖片加載,
-(void)loadAsyncTandemQueue{
[self cleanimage];
[self loadimageViews];

int  iamgecount = 6;
dispatch_queue_t serialQueue = dispatch_queue_create("myThreadQueue1", DISPATCH_QUEUE_SERIAL);//注意queue對象不是指針類型
//創建多個線程用于填充圖片
for (int i=0; i<iamgecount; ++i) {
    //異步執行隊列任務
    dispatch_async(serialQueue, ^{
        [self loadImage:[NSNumber numberWithInt:i]];
    });
  }
}
//異步并行隊列 不會按順序加載
-(void)loadAsyncParallelQueue{
[self cleanimage];

[self loadimageViews];
int  iamgecount = 6;
/*dispatch_get_global_queue(參數1, 參數2);
 取得全局隊列
 第一個參數:線程優先級
 第二個參數:標記參數,目前沒有用,一般傳入0
 */
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//創建多個線程用于填充圖片
for (int i=0; i<iamgecount; ++i) {
    //異步執行隊列任務
    dispatch_async(globalQueue, ^{
        [self loadImage:[NSNumber numberWithInt:i]];
    });
}
}

//    GCD  sync 卡頓.
//    內嵌套一個async 就可以運行起來.

//同步隊列. 同步 無論并行還是串行 也是最后統一加載
//同時會占據主線程,  造成scrollView 不能拖動
-(void)loadsyncParallelQueue{
[self cleanimage];

[self loadimageViews];
int  iamgecount = 6;



dispatch_queue_t syncQueue = dispatch_queue_create("myThreadQueue2", DISPATCH_QUEUE_SERIAL);
//創建多個線程用于填充圖片
for (int i=0; i<iamgecount; ++i) {
   
    //同步執行隊列任務
    dispatch_sync(syncQueue, ^{
        NSLog(@"%@ i = %d",syncQueue,i);
         [self loadImage:[NSNumber numberWithInt:i]];
    });

}
}

-(void)loadTimeQueue{

[self cleanimage];
[self loadimageViews];

int  iamgecount = 6;
dispatch_queue_t serialQueue = dispatch_queue_create("myThreadQueue1", DISPATCH_QUEUE_SERIAL);//注意queue對象不是指針類型
//創建多個線程用于填充圖片
for (int i=0; i<iamgecount; ++i) {
    //異步執行隊列任務
    dispatch_async(serialQueue, ^{
        [self  timeAfter];
        [self loadImage:[NSNumber numberWithInt:i]];
        
    });
}
}


-(void)timeAfter{
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 10);

dispatch_after(time, dispatch_get_main_queue(), ^{

            NSLog(@"10秒后加載一行圖片");
});
}


@end

GCD執行任務的方法并非只有簡單的同步調用方法和異步調用方法,還有其他一些常用方法:

 dispatch_apply():重復執行某個任務,但是注意這個方法沒有辦法異步執行(為了不阻塞線程可以使用dispatch_async()包裝一下再執行)。 
 dispatch_once():單次執行一個任務,此方法中的任務只會執行一次,重復調用也沒辦法重復執行(單例模式中常用此方法)。 
 dispatch_time():延遲一定的時間后執行。 
 dispatch_group_async():實現對任務分組管理,如果一組任務全部完成可以通過dispatch_group_notify()方法獲得完成通知(需要定義dispatch_group_t作為分組標識)。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容