多线程是指,将原本线性执行的任务分开成若干个子任务同步执行。
优点:防止线程“阻塞”,增强用户体验和程序效率。
缺点:代码的复杂程度会大大提高,而且对于硬件的要求也相应地提高。
常见的多线程的编码方式:NSThred;NSOperation;GCD(全称:Grand Central Dispatch)不讲.
一、NSThred的介绍
NSThred
简介:1、创建方式
第一种:直接启动后台线程
[NSThreaddetachNewThreadSelector:@selector(task)toTarget:selfwithObject:nil];
第二种方式:手动启动线程并启动线程
NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(task)object:nil];
[thread start];
第三种方式:NSObject方法(隐式创建并启动线程)
[selfperformSelectorInBackground:@selector(task)withObject:nil];
2、控制线程状态
获取当前线程状态
+ (NSThread *)currentThread;
休眠线程
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
停止线程,不会再次开启任务
+ (void)exit;
互斥锁的优缺点:
优点:能让多条线程按顺序地执行任务。
缺点:需要耗费大量的CPU资源
- (void)viewDidLoad {
[superviewDidLoad];
NSThread *thread1 = [[NSThreadalloc]initWithTarget:selfselector:@selector(threadOneMethod)object:nil];
NSThread *thread2 = [[NSThreadalloc]initWithTarget:selfselector:@selector(threadTwoMethod)object:nil];
[thread1 start];
[thread2 start];
}
-(void )threadOneMethod{
@synchronized(@"nn"){
for (int i=0; i<2; i++) {
NSLog(@"mm");
//循环一次休眠5秒
[NSThreadsleepForTimeInterval:5];
}
}
NSLog(@"thread1 end");
}
-(void )threadTwoMethod{
@synchronized(@"nn"){
for (int i=0; i<3; i++) {
NSLog(@"dd");
sleep(1);
}
}
NSLog(@"thread2 end");
}
结果:
二、NSOperation的介绍
1、配合使用NSOperation和NSOperationQueue也能实现多线程编程。
NSOperation和NSOperationQueue实现多线程的具体步骤:
(1)先将需要执行的操作封装到一个NSOperation对象中2、NSOperation的子类
NSOperation是一个抽象类,不具备封装操作的能力,应使用其子类。
NSOperation子类的3种使用方式:
(2) NSBlockOperation
- (nullableinstancetype)initWithTarget:(id)target selector:(SEL)sel object:(nullableid)arg;
代码:
NSInvocationOperation *operation=[[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(task)object:nil];
- (void)start;
代码:
+ (instancetype)blockOperationWithBlock:(void (^)(void))block;
代码:
NSBlockOperation *operation=[NSBlockOperation blockOperationWithBlock:^{
NSLog(@"11111“);
}];
- (void)addExecutionBlock:(void (^)(void))block;
代码:
[operation addExecutionBlock:^{
NSLog(@"22222”);
}];
3)NSOperationQueue
NSOperationQueue可以调用start方法来执行任务,默认是同步执行。
将线程对象添加到队列的方法
- (void)addOperation:(NSOperation *)op;
- (void)addOperationWithBlock:(void (^)(void))blockNS_AVAILABLE(10_6,4_0);
代码:
NSOperationQueue *operationQueue =[[NSOperationQueuealloc]init];
//获取线程对象
NSOperation *operation = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(task)object:nil];
task方法中的代码:
- (void)task {
NSDate *beginDate = [NSDatedate];
[NSThreadsleepForTimeInterval:3];//让当前线程休眠
NSDate *endDate = [NSDatedate];
NSTimeInterval duration = [endDatetimeIntervalSinceDate:beginDate];
NSLog(@"duration = 耗时:%.2f", duration);
//在主线程中刷新UI
dispatch_async(dispatch_get_main_queue(), ^{
_disPlayLabel.text =@"filish task";
[_indicatorViewstopAnimating];
});
NSLog(@"我是后台线程");
}