简介
iOS的多线程技术,包括
- NSThread
- NSOperation
- 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];
- 创建子类