异步线程GCD
-(void)a_loadGCD
{
//创建队列组
dispatch_group_t group = dispatch_group_create();
//进入这个组
dispatch_group_enter(group);
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)( 5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//这个组的任务完成时离开
dispatch_group_leave(group);
NSLog(@"111-----1111");
});
NSLog(@"1111111");
});
dispatch_group_enter(group);
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)( 3* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//这个组的任务完成时离开
dispatch_group_leave(group);
NSLog(@"222-----222");
});
NSLog(@"22222222");
});
dispatch_group_enter(group);
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)( 1* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//这个组的任务完成时离开
dispatch_group_leave(group);
NSLog(@"3333-----33333");
});
NSLog(@"3333333");
});
//当所有的任务都完成后会发送这个通知
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"GCD_2 三个任务全部完成");
});
}
//信号量
-(void)b_loadGCD
{
//crate的value表示,最多几个资源可访问
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
for (int i = 0; i<5; i++) {
dispatch_async(quene, ^{
//等待信号,当信号总量小于0的时候就会一直等待,否则就继续执行,并让信号总量-1。
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"run 任务 %d",i);
NSInteger arc = arc4random()%4;
NSLog(@"-------%ld",(long)arc);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(arc * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"complete 任务 %d",i);
//完成一个任务,发送一个信号,会让信号总量加1
dispatch_semaphore_signal(semaphore);
});
});
}
}