#import "MainViewController.h"
@implementation MainViewController
- (void)first
{
//休眠1s
[NSThread sleepForTimeInterval:1.0];
NSLog(@"1");
}
- (void)second
{
[NSThread sleepForTimeInterval:2.0];
NSLog(@"2");
}
- (void)third
{
[NSThread sleepForTimeInterval:3.0];
NSLog(@"3");
}
- (void)fourth
{
[NSThread sleepForTimeInterval:4.0];
NSLog(@"4");
}
void add(int a)
{
NSLog(@"%d",a);
}
- (void)buttonClick
{
//c函数直接调用
//add(100);
void (*addAlias)(int) = add;
addAlias(100);
__block int c = 6;
void (^addAliasOc)(int) = ^(int a){
NSLog(@"%d",c);
};
addAliasOc(12);
//GCD,第1种方法,串行,一个一个执行,当第一个执行完毕才能执行下一个
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// [self first];
// [self second];
// [self third];
// [self fourth];
// //获取主线程,用于更新UI
// dispatch_async(dispatch_get_main_queue(), ^{
// ;
// });
// });
//GCD,第2种方法,并行,分时间片执行
//第一个参数抓取一个全局闲置的线程,如果没有则创建
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self first];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self second];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self third];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self fourth];
});
//GCD,第3种方法,串行
// dispatch_queue_t t = dispatch_queue_create(NULL, NULL);
// dispatch_async(t, ^{
// [self first];
// });
// dispatch_async(t, ^{
// [self second];
// });
// dispatch_async(t, ^{
// [self third];
// });
// dispatch_async(t, ^{
// [self fourth];
// });
//
// dispatch_queue_t t1 = dispatch_queue_create(NULL, NULL);
// dispatch_async(t, ^{
// [self first];
// });
//
//串行
// dispatch_queue_t t = dispatch_queue_create(NULL, NULL);
// dispatch_async(t, ^{
// [self first];
// [self second];
// [self third];
// [self fourth];
// });
//GCD,第4种方法,并行
//
// dispatch_group_t group = dispatch_group_create();
//
// dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
// [self first];
// });
// dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
// [self second];
// });
// dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
// [self third];
// });
// dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
// [self fourth];
// });
//
// dispatch_group_notify(group, dispatch_queue_create(0, 0), ^{
// NSLog(@"全部执行完成!");
// });
//串行
// dispatch_group_t group = dispatch_group_create();
// dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
// [self first];
// [self second];
// [self third];
// [self fourth];
// });
//
// dispatch_group_notify(group, dispatch_queue_create(0, 0), ^{
// NSLog(@"全部执行完成!");
// });
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(110, 50, 100, 40);
[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
@end