标签:
把异步任务放到并行队列进行执行,异步任务会在不同的线程中执行。
/*异步执行+并行队列*/ - (IBAction)clickBasic1:(UIButton *)sender { //全局并行队列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //异步执行 dispatch_async(queue, ^{ for (int i = 0; i<2; i++) { NSLog(@"task1:%d",i); } NSLog(@"task1----%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ for (int i = 0; i<2; i++) { NSLog(@"task2:%d",i); } NSLog(@"task2----%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ for (int i = 0; i<2; i++) { NSLog(@"task3:%d",i); } NSLog(@"task3----%@",[NSThread currentThread]); }); }
运行结果如下。异步任务+并行队列组合情况下,每个任务会在不同的线程中同时执行。
对于异步任务放在串行队列中执行时,任务只会在一个新开的线程中,按照顺序进行执行。
/*异步串行队列*/ - (IBAction)clickBasic3:(id)sender { //创建串行队列 dispatch_queue_t queue = dispatch_queue_create("com.hcios", NULL); //异步执行 dispatch_async(queue, ^{ for (int i = 0; i<2; i++) { NSLog(@"task1:%d",i); } NSLog(@"task1----%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ for (int i = 0; i<2; i++) { NSLog(@"task2:%d",i); } NSLog(@"task2----%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ for (int i = 0; i<2; i++) { NSLog(@"task3:%d",i); } NSLog(@"task3----%@",[NSThread currentThread]); }); }
运行结果如下。可以看到,所有任务都在一个线程中执行,并且完成一个后,再执行下一个。
标签:
原文地址:http://www.cnblogs.com/gfxxbk/p/5503643.html