gcd 的特性以及优缺点在此就不多说了
直接上代码:
先声明主子线程对象
dispatch_queue_t _main;
dispatch_queue_t _queue;
实例化他们
//主线程对列也称为串行队列
_main=dispatch_get_main_queue();
//子线程队列也称为并行队列
_queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//先设置一个事件方法
-(void)doSomething:(NSString *)str
{
[NSThreadsleepForTimeInterval:1];
NSLog(@"%@",str);
}
//研究主线程特征
-(void)func1
{
dispatch_async(_main, ^{
[self doSomething:@"A"];
});
dispatch_async(_main, ^{
[self doSomething:@"B"];
});
dispatch_async(_main, ^{
[self doSomething:@"C"];
});
dispatch_async(_main, ^{
[self doSomething:@"D"];
});
}
//研究子线程队列
-(void)func2
{
dispatch_async(_queue, ^{
[self doSomething:@"A"];
});
dispatch_async(_queue, ^{
[self doSomething:@"B"];
});
dispatch_async(_queue, ^{
[self doSomething:@"C"];
});
dispatch_async(_queue, ^{
[self doSomething:@"D"];
});
}
这时,我们观察两个时间戳,就知道是怎么回事了....
//研究自定义队列
-(void)func3
{
//DISPATCH_QUEUE_CONCURRENT并行队列
//DISPATCH_QUEUE_SERIAL 串行队列
dispatch_queue_t customQueue=dispatch_queue_create("a", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(customQueue, ^{
[self doSomething:@"A"];
});
dispatch_async(customQueue, ^{
[self doSomething:@"B"];
});
//添加分割线
dispatch_barrier_async(customQueue, ^{
NSLog(@"============");
});
dispatch_async(customQueue, ^{
[self doSomething:@"C"];
});
dispatch_async(customQueue, ^{
[self doSomething:@"D"];
});
}