OS中多线程有三种,但是一般用俩种。NSThread基本不会用到,需要手动管理线程的生命周期,基本不会使用,GCD底层是NSThread实现的
NSOperation是抽象类,不会直接创建线程,需要子类化,NSInvocationOperation或者NSBlockOperation。见名知意。
使用NSInvocationOperation创建线程对象和操作
<pre name="code" class="objc">#import "ViewController.h"
@interface ViewController ()
- (void)viewDidLoad {
[super viewDidLoad];
//创建线程,指定方法,线程执行即会调用方法
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(handleOperationAction) object:nil];
[operation start];
NSLog(@"%@",[NSThread currentThread]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
输出结果为:2015-10-23 22:04:33.278 nil,NULL,NSNULL[3343:579605] <NSThread: 0x7fa3bac02ec0>{number = 1, name = main}
<pre name="code" class="objc">operation放在哪个线程中start就会再哪个线程中执行,所以此处的线程名为main
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(handleOperation2Action) object:nil]; NSInvocationOperation *operation3 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(handleOperation3Action) object:nil]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [queue addOperation:operation1]; NSArray *operationArr = @[operation3,operation2]; [queue addOperations:operationArr waitUntilFinished:YES];//第二个参数为加锁}-(void)handleOperation1Action{ NSLog(@"1%@",[NSThread currentThread]);}-(void)handleOperation3Action{ NSLog(@"3%@",[NSThread currentThread]);}-(void)handleOperation2Action{ NSLog(@"2%@",[NSThread currentThread]);}</span>
<span style="font-size:14px;"><span style="font-family: monospace; white-space: pre; background-color: rgb(240, 240, 240);"></span></span>
2015-10-23 22:25:38.852 nil,NULL,NSNULL[3511:611985] 2<NSThread: 0x7fc161c090d0>{number = 4, name = (null)}
2015-10-23 22:25:38.852 nil,NULL,NSNULL[3511:611977] 3<NSThread: 0x7fc161f0e940>{number = 3, name = (null)}
2015-10-23 22:25:38.852 nil,NULL,NSNULL[3511:611980] 1<NSThread: 0x7fc161e42e80>{number = 2, name = (null)}
</pre><pre name="code" class="objc">
在加入到operationQueue中,队列会自动执行,不需要手动调用start方法。加入queue中的线程会异步执行,可以从输出台输出的信息验证。
queue可以加入很多个Operation,可以设置queue的最大并发数,默认是-1,表示没有限制。 [queue setMaxConcurrentOperationCount:5],最大并发数为5.
如有不正之处欢迎指正