#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
/*
 GCD共有三种形式的队列
 1.用户队列:通过dispatch_queue_create()方法创建的队列,可以自行定义 并行 或者 串行
 2.The global queue:全局队列。全局队列由系统自动创建,我们通常把要执行的任务放入其中执行,全局队列是并行队列。全局队列拥有优先级的区别(用户界面,用户操作,周期操作,后台,默认)
 3.The main queue:主队列。主队列可以认为就是主线程。主队列必定是放在主线程中执行。主队列是串行的
 */

//全局队列异步
- (IBAction)globalAsync:(UIButton *)sender {
    //获取系统创建的全局对列,这个队列的生命周期与进程一致
    dispatch_queue_t globalQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        for (int i =0; i<10; i++) {
            NSLog(@"i =%d,thread %@",i,[NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        }
    });
    dispatch_async(globalQueue, ^{
        for (int j=0; j<10; j++) {
            NSLog(@"j = %d,thread %@",j,[NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        }
    });
    
    
}

//主队列异步 用得较少
- (IBAction)mainsync:(UIButton *)sender {
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        for (int i =0; i<10; i++) {
            NSLog(@"i =%d,thread %@",i,[NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        }
    });
    dispatch_async(mainQueue, ^{
        for (int j=0; j<10; j++) {
            NSLog(@"j = %d,thread %@",j,[NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        }
    });

    
}

//主队列同步 该方式不会使用,因为会造成死锁
- (IBAction)mainAsync:(UIButton *)sender {
    //此方法要求队列立即执行block中的语句
    //主线程要求排队,因为主线程是串行的。必须等主线程之前的任务做完才能执行block语句。
    //同步 sync 要求线程立即开始执行  异步 async 线程有时间就执行。
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_sync(mainQueue, ^{
        for (int i =0; i<10; i++) {
            NSLog(@"%d",i);
        }
    });
}





- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

@end