码迷,mamicode.com
首页 > 其他好文 > 详细

异步函数

时间:2015-09-02 08:16:00      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

 

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

 

    

    

}

 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    NSLog(@"touchesBegan");

    // 异步函数 + 主队列

    // 结论:1.不会开启新线程

    //     2.任务按顺序执行

    dispatch_async(dispatch_get_main_queue(), ^{

        

         NSLog(@"耗时操作1:%@",[NSThread currentThread]);

    });

    

    dispatch_async(dispatch_get_main_queue(), ^{

        

        NSLog(@"耗时操作2:%@",[NSThread currentThread]);

    });

    

    dispatch_async(dispatch_get_main_queue(), ^{

        

        NSLog(@"耗时操作3:%@",[NSThread currentThread]);

    });

    NSLog(@"touchesEnd");

 

 

}

 

// 异步函数 + 并发队列

// 任务在子线程执行/会开启多条新线程

// 任务同时执行

// 并不是有多少任务就开启多少线程.

- (void)test2

{

    // 异步函数 + 并发队列

    // 任务在子线程执行/会开启多条新线程

    // 任务同时执行

    // 并不是有多少任务就开启多少线程.

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"耗时操作1:%@",[NSThread currentThread]);

    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"耗时操作2:%@",[NSThread currentThread]);

    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"耗时操作3:%@",[NSThread currentThread]);

    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"耗时操作4:%@",[NSThread currentThread]);

    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"耗时操作5:%@",[NSThread currentThread]);

    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"耗时操作6:%@",[NSThread currentThread]);

    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"耗时操作7:%@",[NSThread currentThread]);

    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"耗时操作8:%@",[NSThread currentThread]);

    });

}

 

 

// 异步函数 + 串行队列

// 结论: 1.开启一条线程,任务在新线程中执行.

//       2.任务按顺序执行,在同一条子线程执行.

//       3.一个队列对应一条线程

- (void)test1

{

    // 异步函数 + 串行队列

    // 结论: 1.开启一条线程,任务在新线程中执行.

    //       2.任务按顺序执行,在同一条子线程执行.

    //       3.一个队列对应一条线程

    dispatch_queue_t serialQueue1 = dispatch_queue_create("", DISPATCH_QUEUE_SERIAL);

    dispatch_queue_t serialQueue2 = dispatch_queue_create("", DISPATCH_QUEUE_SERIAL);

    

    dispatch_async(serialQueue1, ^{

        NSLog(@"耗时操作1:%@",[NSThread currentThread]);

    });

    

    dispatch_async(serialQueue2, ^{

        NSLog(@"耗时操作2:%@",[NSThread currentThread]);

    });

    

    dispatch_async(serialQueue2, ^{

        NSLog(@"耗时操作3:%@",[NSThread currentThread]);

    });

    

    dispatch_async(serialQueue1, ^{

        NSLog(@"耗时操作4:%@",[NSThread currentThread]);

    });

}

@end

异步函数

标签:

原文地址:http://www.cnblogs.com/R-X-L/p/4777563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!