多线程

简介

iOS的多线程技术,包括

  1. NSThread
  2. NSOperation
  3. GCD

NSThread

官方文档https://developer.apple.com/documentation/foundation/nsthread

//创建
- (void)createThread{
    for (int i=0; i<10; ++i) {
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(doSomething:) object:[NSNumber numberWithInt:i]];
        thread.name = [NSString stringWithFormat:@"myThread%i",i];//设置线程名称
        thread.threadPriority = 1.0;//优先级,从0-1
        [thread start];
    }
}


还有其他方法
//取消线程
- (void)cancel;

//启动线程
- (void)start;

//判断某个线程的状态的属性
@property (readonly, getter=isExecuting) BOOL executing;
@property (readonly, getter=isFinished) BOOL finished;
@property (readonly, getter=isCancelled) BOOL cancelled;

//设置和获取线程名字
-(void)setName:(NSString *)n;
-(NSString *)name;

//获取当前线程信息
+ (NSThread *)currentThread;

//获取主线程信息
+ (NSThread *)mainThread;

//使当前线程暂停一段时间,或者暂停到某个时刻
+ (void)sleepForTimeInterval:(NSTimeInterval)time;
+ (void)sleepUntilDate:(NSDate *)date;

NSOperation

NSOperation是对GCD的包装,包含NSOperationQueue和NSOperation两个基本要素。
官方文档https://developer.apple.com/documentation/foundation/nsoperation

由于NSOperation是一个抽象类,所以使用的时候,要自己创建其子类,或者直接使用NSInvocationOperation、NSBlockOperation。

使用

  • NSInvocationOperation
NSInvocationOperation *invocationOP = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(processTask) object:nil];
[invocationOP start];
  • NSBlockOperation
NSBlockOperation *blockOP = [NSBlockOperation blockOperationWithBlock:^{
}];
[blockOP start];
  • 创建子类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值