iOS 多线程编程之NSThread

1.NSThread的创建方式

a.动态方法创建

/**
 *  创建NSThread线程
 *
 *  @param target selector消息发送的对象
 *  @param sel    selector消息(即执行方法)
 *  @param arg    传给selector的唯一参数,也可以是nil
 *
 *  @return NSThread线程对象
 */
- (nullable instancetype)initWithTarget:(id)target selector:(SEL)sel object:(nullable id)arg;
eg:
    //创建线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil];
    //让线程开始执行
    [thread start];

b.静态方法创建

/**
 *  创建线程
 *
 *  @param selector selector消息(即执行方法)
 *  @param target   selector消息发送的对象
 *  @param argument 传给selector的唯一参数,也可以是nil
 */
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
eg:
[NSThread detachNewThreadSelector:@selector(threadRun) toTarget:self withObject:nil];

注意:使用静态方法创建NSThread时,创建的线程时默认开始的,如果使用动态方法一定要手动开始。

c.利用隐式创建线程的方法

[self performSelectorInBackground:@selector(reloadMyData) withObject:nil];

2.NSThread常用方法

a.获取当前线程

NSThread *currentThread = [NSThread currentThread];

b.获取主线程

NSThread *mainThread = [NSThread mainThread];

c.暂停当前线程

[NSThread sleepForTimeInterval:0.5];

3.NSThread中各个线程之间的通讯

a.在指定线程上进行操作

[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];

b.在主线程上进行操作

[self performSelectorOnMainThread:@selector(refreshData) withObject:nil waitUntilDone:YES];

c.在当前线程上进行操作

[self performSelector:@selector(run) withObject:nil];

4.NSThread优缺点

优点:

NSThread相比于GCD、NSOperation较轻量级,更能够直接地控制线程对象

缺点:

需要自己管理线程的生命周期以及线程同步,会照成一定的系统开销(线程同步对数据加锁)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值