ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//GCD
//并行(CONCURRENT)任务执行顺序是无序的,若想让某个任务先执行,用障碍block隔开,放到障碍之前;串行(SERIAL)任务执行是有序的,遵循先来后到的原则.
dispatch_queue_t queue = dispatch_queue_create("queue1", DISPATCH_QUEUE_CONCURRENT);
//创建一个分组
dispatch_group_t group1 = dispatch_group_create();
//添加任务到队列中
dispatch_group_async(group1, queue, ^{
NSLog(@"竹");
});
//障碍block,把我们的那些任务分割成两部分,障碍前和障碍后
// dispatch_barrier_async(queue, ^{
// for (int i = 0; i < 1; i++) {
// NSLog(@"11111");
// }
// });
dispatch_group_async(group1, queue, ^{
NSLog(@"川");
});
dispatch_group_async(group1, queue, ^{
NSLog(@"萤");
});
dispatch_group_async(group1, queue, ^{
NSLog(@"火");
});
//可以让某一个事件重复执行
//第一个参数:次数
//第二个参数:所在的队列
//第三个参数:block块
NSArray *array = @[@"大西洋",@"太平洋",@"印度洋",@"喜洋洋"];
dispatch_apply(4, queue, ^(size_t t) {
NSLog(@"绿川幸 %@",array[t]);
});
//延迟执行
//DISPATCH_TIME_NOW表示当前时间
//NSEC_PER_SEC表示1秒
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4
* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"秒速五厘米");
});
//默认的并行的队列(全局队列),只要前面的任务开始执行,不管是否执行完毕,直接开始下一条任务
dispatch_queue_t queue7 = dispatch_get_global_queue(0, 0);
dispatch_async(queue7, ^{
NSLog(@"%@ %d 呱呱",[NSThread currentThread],[NSThread isMainThread]);
});
dispatch_async(queue7, ^{
NSLog(@"%@ %d 长大",[NSThread currentThread],[NSThread isMainThread]);
});
dispatch_async(queue7, ^{
NSLog(@"%@ %d 成熟",[NSThread currentThread],[NSThread isMainThread]);
});
dispatch_async(queue7, ^{
NSLog(@"%@ %d 老去",[NSThread currentThread],[NSThread isMainThread]);
});
dispatch_async(queue7, ^{
NSLog(@"%@ %d 逝世",[NSThread currentThread],[NSThread isMainThread]);
});
//串行
dispatch_queue_t queue8 = dispatch_get_main_queue();
dispatch_async(queue8, ^{
NSLog(@"%@ %d 呱呱",[NSThread currentThread],[NSThread isMainThread]);
});
dispatch_async(queue8, ^{
NSLog(@"%@ %d 长大",[NSThread currentThread],[NSThread isMainThread]);
});
dispatch_async(queue8, ^{
NSLog(@"%@ %d 成熟",[NSThread currentThread],[NSThread isMainThread]);
});
dispatch_async(queue8, ^{
NSLog(@"%@ %d 老去",[NSThread currentThread],[NSThread isMainThread]);
});
dispatch_async(queue8, ^{
NSLog(@"%@ %d 逝世",[NSThread currentThread],[NSThread isMainThread]);
//回到主线程
[self performSelectorOnMainThread:@selector(mainThreadAction) withObject:nil waitUntilDone:YES];
});
// Do any additional setup after loading the view, typically from a nib.
}
-(void)mainThreadAction{
NSLog(@"回来了 %@",[NSThread currentThread]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end