1 初始化队列
1> 主队列--串行队列
dispatch_queue_t mainQueue=dispatch_get_main_queue();
2> 全局并行队列
dispatch_queue_t concu=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
3> 创建串行队列
dispatch_queue_t queueSerial=dispatch_queue_create("jereh1",DISPATCH_QUEUE_SERIAL);
4> 创建并行队列
dispatch_queue_t queueConcu=dispatch_queue_create("jereh2",DISPATCH_QUEUE_CONCURRENT);
2 同步执行
1> 同步+串行
dispatch_sync(queueSerial, ^{
NSLog(@"同步串行对列1---%@",[NSThread currentThread]);
});
dispatch_sync(queueSerial, ^{
NSLog(@"同步串行对列2---%@",[NSThread currentThread]);
});
dispatch_sync(mainQueue, ^{
NSLog(@"--同步--串行--系统--主对列--死锁--不会执行--%@",[NSThread currentThread]);
});
2> 同步+并行
dispatch_sync(queueConcu, ^{
NSLog(@"同步并行队列1---%@",[NSThread currentThread]);
});
dispatch_sync(queueConcu, ^{
NSLog(@"同步并行队列2---%@",[NSThread currentThread]);
});
3 异步执行
1> 异步执行+串行队列-----开启一个子线程,顺序执行
dispatch_async(queueSerial, ^{
NSLog(@"异步串行队列1---%@",[NSThread currentThread]);
});
dispatch_async(queueSerial, ^{
NSLog(@"异步串行队列2---%@",[NSThread currentThread]);
});
2> 异步+并行-----开辟多个子线程,并发执行
dispatch_async(queueConcu, ^{
NSLog(@"异步并行队列1---%@",[NSThread currentThread]);
});
dispatch_async(queueConcu, ^{
NSLog(@"异步并行队列2---%@",[NSThread currentThread]);
});
4 GCD多线程的常用方法
1> 重复执行
dispatch_apply(3, queueSerial, ^(size_t t) {
//循环3次,t是当前执行的第几次
[NSThread sleepForTimeInterval:2];
NSLog(@"---%ld---%@",t,[NSThread currentThread]);
//本身是主线程,位于同一个线程,放在异步里面使用变为子线程里面再开启返回主线程
});
});
2> 分组
dispatch_group_t group=dispatch_group_create();
dispatch_group_async(group, queueConcu, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"--1--");
});
dispatch_group_async(group, queueConcu, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"--2--");
});
dispatch_group_notify(group, queueConcu, ^{
NSLog(@"结束了");//都结束的时候执行
});
3> 延迟执行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//等待2秒
NSLog(@"==延迟执行===%@",[NSThread currentThread]);
});
4> 障碍
dispatch_async(queueConcu, ^{
NSLog(@"=====0");
});
dispatch_barrier_async(queueConcu, ^{//设置障碍,后面的必须等到它执行完再执行
[NSThread sleepForTimeInterval:2];
NSLog(@"=====1");
});
dispatch_async(queueConcu, ^{
NSLog(@"=====2");
});