您的位置:首页 > 其它

GCD几种简单用法

2016-04-09 13:56 162 查看
//1.同步  顺序执行

- (void)test1

{

 
  dispatch_async(mainQueue,
^{

     
  [self doSomeThing:@"A"];

    });

 
  dispatch_async(mainQueue,
^{

    
  [self doSomeThing:@"B"];

    });

 
  dispatch_async(mainQueue,
^{

     
  [self doSomeThing:@"C"];

    });

}

//2.异步同时进行

- (void)test2

{

 
  dispatch_async(globalQueue,
^{

     
  [self doSomeThing:@"A"];

    });

 
  dispatch_async(globalQueue,
^{

     
  [self doSomeThing:@"B"];

    });

 
  dispatch_async(globalQueue,
^{

     
  [self doSomeThing:@"C"];

    });

}

//3.A B同时进行  最后执行C

- (void)test3

{

 
  dispatch_group_t group
= dispatch_group_create();

    

 
  dispatch_group_async(group, globalQueue,
^{

     
  [self doSomeThing:@"A"];

    });

 
  dispatch_group_async(group, globalQueue,
^{

     
  [self doSomeThing:@"B"];

    });

 
  dispatch_group_async(group, globalQueue,
^{

     
  [self doSomeThing:@"C"];

    });

 
  dispatch_group_async(group, globalQueue,
^{

     
  [self doSomeThing:@"D"];

    });

    

 
  dispatch_group_notify(group, globalQueue,
^{

 
   
  [self doSomeThing:[NSString stringWithFormat: @"最后执行----%d",[NSThread isMainThread]]];

 
   
  dispatch_async(mainQueue,
^{

 
     
 
  [self doSomeThing:[NSString stringWithFormat: @"主线程刷新UI----%d",[NSThread isMainThread]]];

     
  });

    });

}

//4.自定义队列
 
自定义执行顺序 
可串行 
可并行

- (void)test4

{

   

 
  dispatch_queue_t customQueue = dispatch_queue_create("anfu",
DISPATCH_QUEUE_CONCURRENT);

    

   dispatch_async(customQueue, ^{

     
  [self
doSomeThing:@"A"];

    });

   dispatch_async(customQueue, ^{

    
  [self
doSomeThing:@"B"];

    });

    

 
  dispatch_barrier_async(customQueue, ^{

     
  [self
doSomeThing:@"C"];

    });

    

   dispatch_async(customQueue, ^{

     
  [self
doSomeThing:@"D"];

    });

   dispatch_async(customQueue, ^{

     
  [self
doSomeThing:@"E"];

    });

    

}

//5.延迟调用

- (void)test5

{

 
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(1 *NSEC_PER_SEC)), dispatch_get_main_queue(),
^{

     
  [self doSomeThing:@"过1秒后执行"];

    });

}

//6.调用多次

- (void)test6

{

    dispatch_apply(10, globalQueue, ^(size_t time)
{

     
  NSLog(@"%zu",time);

    });

}

//7.只调用一次,一般在单例中使用

- (void)test7

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken,
^{

     
  NSLog(@"只调用一次");

    }); 

}

//公共调用方法

- (void)doSomeThing:(NSString *)obj

{

   sleep(1);

   NSLog(@"%@",obj);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: