1.什么是GCD
![](https://img-blog.csdn.net/20160306154346647?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
2.任务和队列
![](https://img-blog.csdn.net/20160306154553323?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
执行任务的方式
![](https://img-blog.csdn.net/20160306154730555?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
队列:串行队列,并行队列,全局队列,主队列
![](https://img-blog.csdn.net/20160306155656340?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
//串行队列 同步执行任务 会在当前线程内执行 # 不一定是主线程
//异步的方式 执行串行队列 会创建一个新的线程来执行任务
//串行的队列都是按照顺序来执行。就是任务1 -> 任务2 -》任务3
-
- -(void)demo
- {
-
-
- dispatch_queue_t queue=dispatch_queue_create("itcast", DISPATCH_QUEUE_SERIAL);
-
-
- dispatch_block_t task1=^{
- NSLog(@"%@ 同步执行了方法1",[NSThread currentThread]);
- };
-
- dispatch_block_t task2=^{
- NSLog(@"%@ 同步执行了方法2",[NSThread currentThread]);
- };
-
-
-
-
-
- dispatch_sync(queue, task1);
-
- dispatch_sync(queue, task2);
-
-
- }
-
-
-
- -(void)demo2
- {
-
-
- dispatch_queue_t queue=dispatch_queue_create("itcast", DISPATCH_QUEUE_SERIAL);
-
-
- dispatch_block_t task1=^{
- NSLog(@"%@ 异步执行了方法1",[NSThread currentThread]);
- };
-
- dispatch_block_t task2=^{
- NSLog(@"%@ 异步执行了方法2",[NSThread currentThread]);
- };
-
-
-
-
-
-
-
- dispatch_async(queue, task1);
-
- dispatch_async(queue, task2);
-
-
- }
并行队列
![](https://img-blog.csdn.net/20160306160215017?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
//并行队列,同步的方式执行 并不会开辟新线程
//异步的方式 执行并行队列 会创建多个新的线程来执行 多个任务 是随机无序执行的
-
- -(void)demo
- {
-
-
- dispatch_queue_t queue=dispatch_queue_create("itcast", DISPATCH_QUEUE_CONCURRENT);
-
-
- dispatch_block_t task1=^{
- NSLog(@"%@ 同步执行了方法1",[NSThread currentThread]);
- };
-
- dispatch_block_t task2=^{
- NSLog(@"%@ 同步执行了方法2",[NSThread currentThread]);
- };
-
-
-
-
-
- dispatch_sync(queue, task1);
-
- dispatch_sync(queue, task2);
-
-
- }
-
-
-
-
- -(void)demo2
- {
-
-
- dispatch_queue_t queue=dispatch_queue_create("itcast", DISPATCH_QUEUE_CONCURRENT);
-
-
- dispatch_block_t task1=^{
- NSLog(@"%@ 异步执行了方法1",[NSThread currentThread]);
- };
-
- dispatch_block_t task2=^{
- NSLog(@"%@ 异步执行了方法2",[NSThread currentThread]);
- };
-
-
-
-
-
-
-
- dispatch_async(queue, task1);
-
- dispatch_async(queue, task2);
-
-
- }
![](https://img-blog.csdn.net/20160306160809306?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
![](https://img-blog.csdn.net/20160306160901026?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
转载自:http://blog.csdn.net/yang__xz/article/details/50813681