IOS多线程(NSThread,NSOperation,Grand Central Dispatch)

•NSThread:

  –优点:NSThread 比其他两个轻量级,使用简单
  –缺点:需要自己管理线程的生命周期、线程同步、加锁、睡眠以及唤醒等。线程同步对数据的加锁会有一定的系统开销
 
•NSOperation

   –不需要关心线程管理,数据同步的事情,可以把精力放在自己需要执行的操作上

   –NSOperation是面向对象的

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

•如果要更新UI界面,可以在后台线程中调用performSelectorOnMainThread方法
 
•提示:尽管使用performSelectorInBackground方法调用的任务可以更新UI界面,但是在实际开发中,涉及到UI界面的更新操作,还是要使用performSelectorOnMainThread   方法,以避免不必要的麻烦
 
•开启后台执行任务的方法
 
  -(void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
 
•在后台线程中通知主线程执行任务的方法
 
  –(void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
 
•获取线程信息
 
  [NSThread currentThread];
 
•线程休眠
 
  [NSThread sleepForTimeInterval:1.0f];
 
 
 + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
 - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
•detachNewThreadSelector方法会直接启动线程方法
•initWithTarget需要调用start方法才能够启动线程方法
•参数说明:
  –selector:线程执行的方法,只能有一个参数,不能有返回值
  –target:selector消息发送的对象
  –argument:传输给target的唯一参数,也可以是nil
 
•NSOperation的两个子类
  1.NSInvocationOperation
  2.NSBlockOperation
•工作原理:
  1.用NSOperation封装要执行的操作
  2.将创建好的NSOperation对象放NSOperationQueue中
  3.启动OperationQueue开始新的线程执行队列中的操作
•注意事项:
  1.使用多线程时通常需要控制线程的并发数,因为线程会消耗系统资源,同时运行的线程过多,系统会变慢
  2.使用以下方法可以控制并发的线程数量:
-(void)setMaxConcurrentOperationCount:(NSInteger)cnt;
原文地址:https://www.cnblogs.com/BinZone/p/3996387.html