今天谈到多线程,那么就来说说多线程。
多线程简介。
第一、为什么使用多线程?
第二、怎么使用多线程?
第三、多线程都有哪些实现方式?
第四、多线程之间怎么实现通信的?
第五、使用多线程有什么缺点?有什么优点?
第六、使用多线程中应该注意什么?
下面一点一点来进行解决:
线程简介:
首先需要理解进程和线程这2个概念。
第一、为什么使用多线程?
IOS 中的多线程包括一下三种方法:NSThread,NSOpreation,GCD(grand central dispatch).
先来看看NSThread:
|
1
2
3
4
5 |
[NSThread
detachNewThreadSelector:@selector(doSomething:) toTarget:self
withObject:nil]; NSThread* myThread = [[NSThread
alloc] initWithTarget:self selector:@selector(doSomething:) object:nil]; [myThread start]; |
selector :线程执行的方法,这个selector只能有一个参数,而且不能有返回值。
target :selector消息发送的对象
argument:传输给target的唯一参数,也可以是nil
第一种方式会直接创建线程并且开始运行线程,第二种方式是先创建线程对象,然后再运行线程操作,在运行线程操作前可以设置线程的优先级等线程信息。
再看看NSOperation:
NSOperation和NSOperationQueue
NSOperation 这个类必须要继承并重写里面的方法,才能够使用,不能直接使用NSOperation来实例化对象。
1、一个继承自 NSOperation的操作类,该类的实现中必须有 - (void)main方法的。
2、使用NSOperation的最简单方法就是将其放入NSOperationQueue中。
一旦一个操作被加入队列,该队列就会启动并开始处理它(即调用该操作类的main方法)。一旦该操作完成队列就会释放它。
self.queue = [[NSOperationQueue alloc] init];
ArticleParseOperation *parser = [[ArticleParseOperation alloc] initWithData:filePath delegate:self];
[queue addOperation:parser];
3、可以给操作队列设置最多同事运行的操作数: [queue setMaxConcurrentOperationCount:2];
线程同步
在以下两种基本情况下,线程之间需要相互通信:
什么情况下使用线程同步:
基本思路是,首先要创建公用的NSCondition实例。
使用NSCondition,实现多线程的同步,即,可实现生产者消费者问题。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 |
- (IBAction)didClickTest:(id)sender { _publicCondition = [[NSCondition
alloc]init]; _products = [[NSMutableArray
alloc] init]; NSThread
*thread1 = [[NSThread
alloc]initWithTarget:self
selector:@selector(didClickCreateSCZ:) object:nil]; NSThread
*thread2 = [[NSThread
alloc]initWithTarget:self
selector:@selector(didClickCreateXFZ:) object:nil]; [thread1 start]; [thread2 start]; }- (IBAction)didClickCreateSCZ:(id)sender { [_publicCondition lock]; while
([_products count] == 0) { NSLog(@"wait for products"); [_publicCondition wait]; } [_products removeObjectAtIndex:0]; NSLog(@"comsume a product"); [_publicCondition unlock];}- (IBAction)didClickCreateXFZ:(id)sender { [_publicCondition lock]; [_products addObject:[[NSObject
alloc] init]]; NSLog(@"produce a product"); [_publicCondition signal]; [_publicCondition unlock];} |
原文:http://www.cnblogs.com/yinyakun/p/3580915.html