多线程经常使用的函数

 

#import "ViewController.h"

#import "LZJPerson.h"

@interface ViewController ()

 

@end

 

@implementation ViewController

 

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

{

//    [self delay];

    LZJPerson *P1 = [[LZJPerson alloc]init];

    LZJPerson *P2 = [[LZJPerson alloc]init];

    NSLog(@"%@------%@",P1.book,P2.book);

 

}

 

- (void)delay{

 

    NSLog(@"start---");

//    1.延迟执行的第一种方法

//    [self performSelector:@selector(task) withObject:nil afterDelay:2.0];

    

//    2.延迟执行的第二种方法

//    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:YES];

    

//    第三种 GCD

// dispatch_queue_t queue =  dispatch_get_main_queue();

    dispatch_queue_t queue =dispatch_get_global_queue(0, 0);

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)),queue , ^{

        NSLog(@"GCD---%@",[NSThread currentThread]);

        

    });

    

}

//一次性代码----注意不能放在懒加载里面使用 

- (void)once{

 

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        NSLog(@"------hello");

    });

 

}

 

- (void)task{

 

    NSLog(@"task---%@",[NSThread currentThread]);

 

}

 

 

GCD中还有个用来执行任务的函数:

dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block);

在前面的任务执行结束后它才执行,而且它后面的任务等它执行完成之后才会执行

这个queue不能是全局的并发队列

@end

原文地址:https://www.cnblogs.com/liuzhenjie/p/5202877.html