ios有三种主要方法:1、NSThread。2、NSOperation。3、GCD。
1、 NSThread:
调用方法如下:如果需要函数参数的话,可以通过Object传递。
1.1:NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadInMainMethod:) object:nil];
[myThread start];
1.2:[NSThread detachNewThreadSelector:@selector(threadInMainMethod:) toTarget:self withObject:nil];
1.3: [obj performSelectorInBackground:@selector(threadMe) withObject:nil];
2、 NSOperation:
NSOperation是一个任务,一个NSOperationQueue至少拥有一个线程,可配置。
NSOperationQueue *queue = [[[NSOperationQueue alloc ] init] autorelease];
TestNSOperation *testNSOperation=[[[TestNSOperation alloc ] init] autorelease];//TestNSOperation继承NSOperation
[queue addOperation:testNSoperation];
NSInvocationOperation是NSOperation的一种实现
NSInvocationOperation *invocOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomeThing)
object:nil];
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init]; [aQ setMaxConcurrentOperationCount:10]; [operationQueue addOperation:invocOperation];
NSOpertaion有2种形式.
(1) 并发执行
并发执行你需要重载如下4个方法
//执行任务主函数,线程运行的入口函数
- (void)start
//是否允许并发,返回YES,允许并发,返回NO不允许。默认返回NO
-(BOOL)isConcurrent
- (BOOL)isExecuting
//是否已经完成,这个必须要重载,不然放在放在NSOperationQueue里的NSOpertaion不能正常释放。
- (BOOL)isFinished
(2)非并发执行
-(void)main
只需要重载这个main方法就可以了。
3、 GCD
GCD是和block紧密相连的,所以最好先了解下block(可以查看这里).GCD是C level的函数,这意味着它也提供了C的函数指针作为参数,方便了C程序员.
下面首先来看GCD的使用:
dispatch_async(dispatch_queue_t queue, dispatch_block_t block); |
async表明异步运行,block代表的是你要做的事情,queue则是你把任务交给谁来处理了.有三种queue。一个queue相当于一个线程。
1. 主线程队列 Main queue:
顾名思义,运行在主线程,由dispatch_get_main_queue获得.和ui相关的就要使用Main Queue.
2.串行的队列 Serial quque(private dispatch queue)
每次运行一个任务,可以添加多个任务,执行次序FIFO. 通常是指程序员生成的,比如:
1 |
dispatch_queue_t myQueue = dispatch_queue_create(queueName, NULL); |
3.并行队列 Concurrent queue(global dispatch queue):
可以同时运行多个任务,每个任务的启动时间是按照加入queue的顺序,结束的顺序依赖各自的任务.使用dispatch_get_global_queue获得.
所以我们可以大致了解使用GCD的框架:
1 2 3 4 5 6 7 |
dispatch_async(queue,^{//获取数据,获得一组后,刷新UI. dispatch_aysnc (mainQueue, ^{//UI的更新需在主线程中进行}; } ); |
由此可见,GCD的使用非常简单,以我的使用经验来看,以后会逐步淘汰使用NSOperation而改用GCD。
提个问题:如果某个ViewController里运行了一个Thread,Thread还没结束的时候,这个ViewController被Release了,结果会如何?
经过的的测试,Thread不结束,ViewController一直保留,不会执行dealloc方法。
相关推荐
iOS线程同步方案,包括各种互斥锁,自旋锁,递归锁等深度解析!!!!
本实例写了一个多线程,从中您可以学到线程创建,线程同步,等基本知识。
iOS 线程资料汇总 iOS 线程使用例子及iOS并发编程指南及代码
iOS线程安全,读写锁,栅栏函数等深度解析,多读单写保证公共资源安全!
IOS线程学习文档+实例代码,特别适合新手学习,超好
ios多线程开发的常用四种方式和基本使用,pthread、NSThread、NSOperation\NSOperationQueue、GCD
ios多线程编程指南,包含NSThread,CGD等,深入简出讲解ios多线程原理和应用
这是一篇介绍IOS多线程理解的文章,简洁易懂,方便阅读
iOSGCD控制多线程任务数量,直接使用ZKRGlobalQueue^()。
原理与使用方法请查看 http://blog.csdn.net/hursing/article/details/8688872
主要介绍了IOS 线程死锁详细介绍的相关资料,需要的朋友可以参考下
关于iOS 多线程编程知识点,iOS 多线程 NSThread NSOperation GCD
多线程编程指南,ios
iOS多线程面试题
iOS多线程编程指南!!
iOS开发多线程,NSoperetion, GCD,多线程的网络图片的下载
iOS开发学习之iOS多线程和RunLoop.pdf
ios 多线程NSoperation
iOS常见的多线程:GCD 任务和队列,异步执行 + 并发队列,线程锁,信号量
iOS多线程,四种实现方式中最简单的两种pthread,NSThread的用法介绍。