#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)groupMethod {
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < 9; i++) {
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
int x = arc4random() % 5;
sleep(x);
NSLog(@"group 请求成功OR请求失败 %d!",i);
dispatch_group_leave(group);
});
}
NSLog(@"group开始 网络请求!");
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"group所有请求完毕!!!");
});
}
- (void)semaphoreMethod {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
for (int i = 0; i < 9; i++) {
NSLog(@"当前线程:%@",[NSThread currentThread]);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
int x = arc4random() % 2;
sleep(x);
NSLog(@"执行任务代号:%d",i);
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
});
}
- (void)groupSemaphoreMethod {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
dispatch_group_t group = dispatch_group_create();
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
for (int i = 0; i < 9; i++) {
dispatch_group_async(group,dispatch_get_global_queue(0, 0), ^{
NSLog(@"执行任务:%d 线程:%@",i,[NSThread currentThread]);
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"所有任务执行完毕!!!");
});
});
}
- (void)serialMethod {
dispatch_queue_t queue = dispatch_queue_create("serial",DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"1---%@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:5];
NSLog(@"xxxxxxxxxxxxxx");
});
dispatch_async(queue, ^{
NSLog(@"2---%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"3---%@", [NSThread currentThread]);
});
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self semaphoreMethod];
}
@end