dispatch 用得最多的是全局队列的异步任务(耗时操作)、主线程队列异步任务(更新UI)、串行队列异步任务(需要顺序执行的耗时操作)
注意事项:主线程队列里面不能有同步任务,会阻塞
ARC里面不需要手动release
代码如下:
//
// ViewController.m
// GCDLearn
//
// Created by wusiping on 15/11/29.
// Copyright (c) 2015年 wusiping. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self globalQueue];
}
- (void)serailQueue
{
dispatch_queue_t q = dispatch_queue_create("cn.wsp.gcddemo", DISPATCH_QUEUE_SERIAL);
//串行队列,先进先出,异步任务先进去,就先执行异步任务,完了再执行同步任务
for (int i = 0 ; i < 5 ; i ++) {
dispatch_async(q, ^{
NSLog(@"串行队列的异步任务是在第二个线程中顺序执行的----%@----%d",[NSThread currentThread],i );
});
}
for (int i = 0 ; i < 5 ; i ++ ) {
dispatch_sync(q, ^{
NSLog(@"串行队列同步任务是在主线程中顺序执行的----%@---%d ",[NSThread currentThread ],i);
});
}
}
- (void)concurrentQueue
{
dispatch_queue_t q = dispatch_queue_create("cn.wsp.gcddemo", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0 ; i < 5 ; i ++) {
dispatch_async(q, ^{
NSLog(@"并行队列,异步任务在多个线程中并发执行---%@--%d",[NSThread currentThread],i);
});
}
for (int i = 0 ; i < 5 ; i ++) {
dispatch_sync(q, ^{
NSLog(@"并行队列,同步任务仍然是在主线程中顺序执行---%@--%d",[NSThread currentThread],i);
});
}
}
- (void)globalQueue
{
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
for (int i = 0 ; i < 5 ; i ++) {
dispatch_sync(q, ^{
NSLog(@"全局队列,同步任务在主线程中顺序执行---%@--%d",[NSThread currentThread],i);
});
}
for (int i = 0 ; i < 5 ; i ++) {
dispatch_async(q, ^{
NSLog(@"全局队列,异步任务在多个线程中并发执行---%@--%d",[NSThread currentThread],i);
});
}
}
- (void)mainQueue
{
dispatch_queue_t q = dispatch_get_main_queue();
/*
for (int i = 0 ; i < 5 ; i ++) {
dispatch_sync(q, ^{
NSLog(@"主线程队列,同步任务会被阻塞---%@--%d",[NSThread currentThread],i);
});
}
*/
for (int i = 0 ; i < 5 ; i ++) {
dispatch_async(q, ^{
NSLog(@"主线程队列,异步任务会在主线程上顺序执行,通常用于更新UI---%@--%d",[NSThread currentThread],i);
});
}
}
@end