1 //
2 // ViewController.m
3 // NSThread
4 //
5 // Created by ys on 15/11/22.
6 // Copyright (c) 2015年 ys. All rights reserved.
7 //
8
9 #import "ViewController.h"
10
11 @interface ViewController ()
12
13 @end
14
15 @implementation ViewController
16
17 - (void)viewDidLoad {
18 [super viewDidLoad];
19 [self GCD1]; //串行队列
20 // [self GCD2]; //并行队列
21 // [self GCD3]; //全局队列
22 // [self GCD4]; //主(线程)队列
23 }
24
25 -(void)GCD1
26 {
27 //串行队列
28 dispatch_queue_t q = dispatch_queue_create("GCD1", DISPATCH_QUEUE_SERIAL);
29
30 for (int i = 0; i<10; i++) {
31 // 异步任务,串行执行,会依次顺序执行
32 dispatch_async(q, ^{//异步执行(同步执行dispatch_sync则任务会全部由主线程串行执行,不会创建新线程,开发中一般不会用到)
33 NSLog(@"%@------%d",[NSThread currentThread],i);
34 });
35 }
36
37 for (int i = 0; i<10; i++) {//主线程
38 NSLog(@"%@--%d",[NSThread currentThread],i);
39 }
40 }
41 //执行结果
42 -(void)GCD2
43 {
44 //并行队列
45 // 特点:没有队形,执行顺序程序员不能控制!
46 // 应用场景:并发执行任务,没有先后顺序关系
47 dispatch_queue_t q = dispatch_queue_create("GCD2", DISPATCH_QUEUE_CONCURRENT);
48 for (int i = 0; i<10; i++) {
49 // 异步任务,并发执行,但是如果在串行队列中,仍然会依次顺序执行
50 dispatch_async(q, ^{//异步执行
51 NSLog(@"%@------%d",[NSThread currentThread],i);
52 });
53 }
54 for (int i = 0; i<10; i++) {
55 NSLog(@"%@--%d",[NSThread currentThread],i);
56 }
57 }
58
59 -(void)GCD3
60 {
61 //全局队列
62 // 全局队列与并行队列的区别
63 // 1> 不需要创建,直接GET就能用
64 // 2> 两个队列的执行效果相同
65 // 3> 全局队列没有名称,调试时,无法确认准确队列
66
67 dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
68 for (int i = 0; i<10; i++) {
69 dispatch_async(q, ^{//异步执行
70 NSLog(@"%@------%d",[NSThread currentThread],i);
71 });
72 }
73 for (int i = 0; i<10; i++) {
74 NSLog(@"%@--%d",[NSThread currentThread],i);
75 }
76 }
77
78 -(void)GCD4
79 {
80 //主(线程)队列
81 dispatch_queue_t q = dispatch_get_main_queue();
82 for (int i = 0; i<10; i++) {
83 dispatch_async(q, ^{//异步执行.如果加入同步队列则造成主线程阻塞
84 NSLog(@"%@------%d",[NSThread currentThread],i);
85 });
86 }
87 for (int i = 0; i<10; i++) {
88 NSLog(@"%@--%d",[NSThread currentThread],i);
89 }
90 }
91 @end