作者刘文涛
转载请注明出处
一、简单介绍
iOS支持多个层次的多线程编程,层次越高的抽象程度越高,使用也越方便,也是苹果最推荐的使用方法。下面根据抽象层次从低到高依次列出iOS所支持的多线程编程方法:
1.Thread:是三种方法里相对轻量级的,但是需要管理线程的生命周期、同步、加锁问题,这会导致一定的性能开销;
2.Cocoa Operations:是基于OC实现的,NSOperation以面向对象的方式封装了需要执行的操作,不必关心线程管理、同步等问题。NSOperation是一个抽象基类,iOS提供了两种默认实现:NSInvocationOperation和NSBlockOperation,当然也可以自定义NSOperation;
3.Grand Central Dispatch(简称GCD,iOS4才开始支持的):提供了一些新特性、运行库来支持多核并行编程,它的关注点更高:如何在多个CPU上提升效率;
这篇文章简单的介绍了第一种多线程的编程方式,主要利用NSThread这个类,一个NSThread实例代表着一条多线程。
二、NSthread的初始化
1.动态方法
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument NS_AVAILABLE(10_5, 2_0);
参数解析:
target:selector消息发送的对象
selector:线程执行的方法,这个selector最多只能接收一个参数
argument:传给selector的唯一参数,也可以是nil
|
|
2.静态方法
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
|
|
3.隐式创建线程的方法
[self performSelectorInBackground:@selector(run) withObject:nil];
三、获取当前线程
NSThread *current = [NSThread currentThread];
四、获取主线程
NSThread *mainThread = [NSThread mainThread];
五、暂停当前线程
//暂停2.0s
[NSThread sleepForTimeInterval:2.0];
//或者
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:date];
六、线程间的通信
1.在指定线程上执行操作
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
2.在主线程上执行操作
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
3.在当前线程执行操作
[self performSelector:@selector(run) withObject:nil];
七、优缺点
优点:NSTread比其他两种多线程方案较轻量级,更直观的控制线程对象
缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据加锁或有一定的系统开销。