@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[selfdemo];
}
//GCD 基础
-(void)demo{
/* //用block语法写
void(^mytask)(void) = ^{};
//创建任务
dispatch_block_t task = ^{
NSLog(@"%@",[NSThread currentThread]);
};
//获取队列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//把任务放入队列中
dispatch_async(queue, task);
//简单写法 工作中常用代码
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"NSThread %@",[NSThread currentThread]);
});
*/
//多个任务
for (int i =0; i <20; i++) {
dispatch_async(dispatch_get_global_queue(0,0), ^{
[NSThreadsleepForTimeInterval:3];
NSLog(@"NSThread %@ %d",[NSThreadcurrentThread],i);
});
}
}
//串行队列 同步执行
//不开线程,在当前线程下执行
//任务是有序执行的
-(void)demo1{
//创建队列 参数1:队列名称 参数2:队列属性
dispatch_queue_t serialqueue =dispatch_queue_create("serialqueue",DISPATCH_QUEUE_SERIAL);
for (int i =0; i <20; i++) {
dispatch_sync(serialqueue, ^{
NSLog(@"%@ %d",[NSThreadcurrentThread],i);
});
}
}
//串行队列 异步执行
//开一个线程
//任务是有序执行的
-(void)demo2{
dispatch_queue_t serialqueue =dispatch_queue_create("serialqueue",DISPATCH_QUEUE_SERIAL);
for (int i =0; i <20; i++) {
dispatch_async(serialqueue, ^{
NSLog(@"%@ %d",[NSThreadcurrentThread],i);
});
}
}
//并行队列 异步执行(效率最大化)
//开多个线程
//任务是无序执行的
-(void)demo3{
dispatch_queue_t concurrentQueue =dispatch_queue_create("concurrentQueue",DISPATCH_QUEUE_CONCURRENT);
for (int i =0; i <20; i++) {
dispatch_async(concurrentQueue, ^{
NSLog(@"%@ %d",[NSThreadcurrentThread],i);
});
}
}
//并行队列 同步执行 (并行无效,按同步执行)与串行同步一样
//不开线程,在当前线程下执行
//任务是有序执行的
-(void)demo4{
dispatch_queue_t concurrentQueue =dispatch_queue_create("concurrentQueue",DISPATCH_QUEUE_CONCURRENT);
for (int i =0; i <20; i++) {
dispatch_sync(concurrentQueue, ^{
NSLog(@"%@ %d",[NSThreadcurrentThread],i);
});
}
}
//主队列异步执行
//不开线程,在主线程下执行
//任务是有序执行的
-(void)demo5{
//获取主线程
dispatch_queue_t mainqueue =dispatch_get_main_queue();
for (int i =0; i <20; i++) {
dispatch_async(mainqueue, ^{
NSLog(@"main queue %@ %d",[NSThreadcurrentThread],i);
});
}
}
//主队列同步执行
//死锁:在主线程下,往主线程里添加同步任务
//解决办法:1,将主线程改子线程 2,同步改为异步
-(void)demo6{
//获取主线程
dispatch_queue_t mainqueue =dispatch_get_main_queue();
dispatch_sync(mainqueue, ^{
NSLog(@"main queue %@",[NSThreadcurrentThread]);
});
}