NSThread,NSOperation,GCD 抽象层次是从低到高的,抽象度越高的使用越简单。
NSThread
优点:在所有的多线程实现方式中 最轻量级。比其它两个更轻。
可以按照需求 任意控制thread对象 即:线程的加锁等操作
缺点:需要自己维护线程的生命周期和线程的同步和互斥,但是这些都需要耗费系统的资源。控制太繁琐 不能自己控制线程安全
//NSThread 的一个对象 就代表一个线程
//创建 NSThread对象
[NSThread detachNewThreadSelector:@selector(threadStart:) toTarget:self withObject:nil];
thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadStart:) object:nil];
// 指定名称
thread.name = @"yy";
//开启NSThread
[thread start];
//取消thread运行
[thread cancel];
// 判断当前任务是否为主线程 0为不是 1为是
BOOL b = [NSThread isMainThread];
NSOperation
NSOperation代表一个任务 自己不能实现多线程。NSOperationQueue可以实现多线程
NSOperation是一个抽象类 不能直接使用, 需要创建一个子类去编写实现的内容,子类NSBlockOperation、NSInvocationOperation
不需要自己管理线程的生命周期和线程的同步和互斥等。只是需要关注自己的业务逻辑处理,需要和NSOperationQueue一起使用
NSOperation * op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationRun:) object:nil];
[op start];
// 任务队列(NSOperationQueue) 内部管理一系列的线程
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//最大并发线程数量
queue.maxConcurrentOperationCount = 3;
for (int i = 0 ; i< 5; i++) {
NSInvocationOperation * op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationRun:) object:nil];
op.name = [NSString stringWithFormat:@"InvocationOperation%d",i];
[queue addOperation:op];
}
GCD 是基于队列的 多线程实现方式
比前面两者更高效更强大,更方便。
参考