多线程

作者: iOS程序媛ing | 来源:发表于2018-03-19 17:56 被阅读8次

    线程有三种创建方式:NSThred、NSOperation、GCD

    这三种方式的发展是从早到晚的,所以后者更加简洁方便,GCD 是目前苹果最推崇的方式

    NSOperation是基于oc的,GCD是基于c的

    NSOperation可以设置线程间依赖的依赖关系、及优先级,GCD虽然也可以做到,但是相对复杂,一般涉及到依赖关系或监听任务完成状态的用NSOperation,其他的用GCD

    1、NSThread

    1.1、NSThread有两种直接创建线程的方式:类方法和实例方法

    实例方法

    - (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument ;

    - (instancetype)initWithBlock:(void (^)(void))block );

    类方法

    + (void)detachNewThreadWithBlock:(void (^)(void))block );

    + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;

    1⃣️使用实例方法先创建线程对象,然后再调用start方法运行线程,可以设置线程名称等;

    2⃣️使用类方法直接创建线程并且开始运行线程,不可以设置线程名称等;

    3⃣️不显示创建线程的方法

    1.2、间接创建线程方法

    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;

    //在主线程添加任务

    当wait为YES时,先执行aSelector方法,在执行perform方法后面的方法,当wait为NO时,先执行perform后面的方法,再执行aSelector方法

    1.3、其他方法

    + (void)sleepUntilDate:(NSDate *)date;

    + (void)sleepForTimeInterval:(NSTimeInterval)ti;

    - (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg );//后台线程

    2、GCD和NSOperation对比

    1⃣️GCD是基于c的,NSOperation是对GCD的封装,提供更多的方法

     2⃣️NSOperation可以取消任务执行,也只能是取消还未执行的任务的执行,GCD其实也是可以取消的,只是代码更佳复杂

    3⃣️NSOperation可以设置任务的优先级,可以在某特定任务执行完毕后再去执行其他任务,GCD也可以,但是需要用刀barrie和group,相比NSOperation更佳复杂

    4⃣️GCD执行顺序是FIFO

    相关文章

      网友评论

          本文标题:多线程

          本文链接:https://www.haomeiwen.com/subject/phulqftx.html