浅谈IOS多线程

来源:互联网 发布:路由器端口限速设置 编辑:程序博客网 时间:2024/05/16 23:02
针对于IOS的多线程的问题, 主要有以下知识点:
1. 进程和主线程: 每一个应用程序就是一个进程, 每一个进程至少有一个线程, 叫做主线程. 主线程在程序启动是被创建, 用于执行main函数, 只有一个主线程的程序是单线程程序, 主线程负责程序的所有代码(网络请求, 本地存储, UI界面等等), 所有代码顺序执行
2.  拥有多个线程的程序是多线程, ios中允许用户开辟新的线程, 相对于主线程, 开辟的线程称作子线程
3. 单 多线程的区别: 单线程代码顺序执行, 容易出现代码阻塞现象, 因此, 多线程可以解决单线程的代码阻塞现象, 提高了代码的执行效率, 改善了程序的性能.但是针对于UI界面, 要放在主线程中运行
4. 多线程的实现方式主要有4种, NSTread NSOperationQueue NSObject GCD
先创建一个有一定功能的方法(在MRC下, 在此注意要将其放进自动释放池) 
  -(void)calculacor
{
for(int i = 0, i < 10000000, i++)
NSLog(@"%d", i);
 }
(1) NSTread
NSTread *thread = [NSTread alloc]initWithTarget:self selector:@selector(calculator) object:nil];
[thread start];
[thread release];
将NSTread作为一个buttonAction的功能, 通过上面的多线程创建, 可以很清晰的看到控制台的显示结果
(2) NSObject
调用方法实现self preformSelectorInBackground:@delector(calculator)withObject:nil;
(3) NSOperation和NSOperationQueue
因为NSOperation是NSBlockOperation和NSInvocationOperation的父类, 因此创建他们的对象添加到NSOperationQueue所开辟的队列中, 还可以自定义继承NSOperation的类, 将对象添加到进程中
NSOpreationQueue *queue = [[NSOperationQueue alloc]init];
CustomOperation *custom = [[CustomOperation alloc]init];
NSBlockOperation *ope = [NSBlockOperation blockOperationWithBlock:^{
@autoreleasepool {
for(int i = 0; i < 12345; i++)
NSLog(@"%d", i);
}
}];
NSInvcationOperation *inv = [[NSInvcationOption alloc]initWithTarget:self selector:@selector(calulacor) object:nil];


[queue addOperation:custom];
[queue addOperation:custom];
[queue addOperation:inv];
通过以上代码, 我们可以清晰看到用NSOperation和NSOperationQueue创建多进程




0 0