转载自:iOS多线程全套:线程生命周期,多线程的四种解决方案,线程安全问题,GCD的使用,NSOperation的使用
下图是线程状态示意图,从图中可以看出线程的生命周期是:新建 - 就绪 - 运行 - 阻塞 - 死亡。
下面分别阐述线程生命周期中的每一步
多线程的四种解决方案分别是:pthread,NSThread,GCD, NSOperation。下图是对这四种方案进行了解读和对比。
NSThread有三种创建方式:
/** 方法一,需要start */
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething1:) object:@"NSThread1"];
// 线程加入线程池等待CPU调度,时间很快,几乎是立刻执行
[thread1 start];
/** 方法二,创建好之后自动启动 */
[NSThread detachNewThreadSelector:@selector(doSomething2:) toTarget:self withObject:@"NSThread2"];
/** 方法三,隐式创建,直接启动 */
[self performSelectorInBackground:@selector(doSomething3:) withObject:@"NSThread3"];
- (void)doSomething1:(NSObject *)object {
// 传递过来的参数
NSLog(@"%@",object);
NSLog(@"doSomething1:%@",[NSThread currentThread]);
}
- (void)doSomething2:(NSObject *)object {
NSLog(@"%@",object);
NSLog(@"doSomething2:%@",[NSThread currentThread]);
}
- (void)doSomething3:(NSObject *)object {
NSLog(@"%@",object);
NSLog(@"doSomething3:%@",[NSThread currentThread]);
}
// 当前线程
[NSThread currentThread];
NSLog(@"%@",[NSThread currentThread]);
// 如果number=1,则表示在主线程,否则是子线程
打印结果:{number = 1, name = main}
//休眠多久
[NSThread sleepForTimeInterval:2];
//休眠到指定时间
[NSThread sleepUntilDate:[NSDate date]];
//退出线程
[NSThread exit];
//判断当前线程是否为主线程
[NSThread isMainThread];
//判断当前线程是否是多线程
[NSThread isMultiThreaded];
//主线程的对象
//线程是否在执行
thread.isExecuting;
//线程是否被取消
thread.isCancelled;
//线程是否完成
thread.isFinished;
//是否是主线程
thread.isMainThread;
//线程的优先级,取值范围0.0到1.0,默认优先级0.5,1.0表示最高优先级,优先级高,CPU调度的频率高
thread.threadPriority;
// 串行队列
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
// 并发队列
dispatch_queue_t queue1 = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 耗时操作放在这里
dispatch_async(dispatch_get_main_queue(), ^{
// 回到主线程进行UI操作
});
});
//全局并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//全局并发队列的优先级
#define DISPATCH_QUEUE_PRIORITY_HIGH 2 // 高优先级
#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0 // 默认(中)优先级
#define DISPATCH_QUEUE_PRIORITY_LOW (-2) // 低优先级
#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN // 后台优先级
//iOS8开始使用服务质量,现在获取全局并发队列时,可以直接传0
dispatch_get_global_queue(0, 0);
代码如下:
// 同步执行任务
dispatch_sync(dispatch_get_global_queue(0, 0), ^{
// 任务放在这个block里
NSLog(@"我是同步执行的任务");
});
// 异步执行任务
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 任务放在这个block里
NSLog(@"我是异步执行的任务");
});
由于有多种队列(串行/并发/主队列)和两种执行方式(同步/异步),所以他们之间可以有多种组合方式。
/** 串行同步 */
- (void)syncSerial {
NSLog(@"\n\n**************串行同步***************\n\n");
// 串行队列
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
// 同步执行
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"串行同步1 %@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"串行同步2 %@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"串行同步3 %@",[NSThread currentThread]);
}
});
}
//输出结果为顺序执行,都在主线程:
串行同步1 {number = 1, name = main}
串行同步1 {number = 1, name = main}
串行同步1 {number = 1, name = main}
串行同步2 {number = 1, name = main}
串行同步2 {number = 1, name = main}
串行同步2 {number = 1, name = main}
串行同步3 {number = 1, name = main}
串行同步3 {number = 1, name = main}
串行同步3 {number = 1, name = main}
/** 串行异步 */
- (void)asyncSerial {
NSLog(@"\n\n**************串行异步***************\n\n");
// 串行队列
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
// 异步执行
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"串行异步1 %@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"串行异步2 %@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"串行异步3 %@",[NSThread currentThread]);
}
});
}
//输出结果为顺序执行,有不同线程:
串行异步1 {number = 3, name = (null)}
串行异步1 {number = 3, name = (null)}
串行异步1 {number = 3, name = (null)}
串行异步2 {number = 3, name = (null)}
串行异步2 {number = 3, name = (null)}
串行异步2 {number = 3, name = (null)}
串行异步3 {number = 3, name = (null)}
串行异步3 {number = 3, name = (null)}
串行异步3 {number = 3, name = (null)}
/** 并发同步 */
- (void)syncConcurrent {
NSLog(@"\n\n**************并发同步***************\n\n");
// 并发队列
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
// 同步执行
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"并发同步1 %@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"并发同步2 %@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"并发同步3 %@",[NSThread currentThread]);
}
});
}
//输出结果为顺序执行,都在主线程
并发同步1 {number = 1, name = main}
并发同步1 {number = 1, name = main}
并发同步1 {number = 1, name = main}
并发同步2 {number = 1, name = main}
并发同步2 {number = 1, name = main}
并发同步2 {number = 1, name = main}
并发同步3 {number = 1, name = main}
并发同步3 {number = 1, name = main}
并发同步3 {number = 1, name = main}
/** 并发异步 */
- (void)asyncConcurrent {
NSLog(@"\n\n**************并发异步***************\n\n");
// 并发队列
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
// 异步执行
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"并发异步1 %@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"并发异步2 %@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"并发异步3 %@",[NSThread currentThread]);
}
});
}
//输出结果为无序执行,有多条线程
并发异步1 {number = 3, name = (null)}
并发异步2 {number = 4, name = (null)}
并发异步3 {number = 5, name = (null)}
并发异步1 {number = 3, name = (null)}
并发异步2 {number = 4, name = (null)}
并发异步3 {number = 5, name = (null)}
并发异步1 {number = 3, name = (null)}
并发异步2 {number = 4, name = (null)}
并发异步3 {number = 5, name = (null)}
/** 主队列同步 */
- (void)syncMain {
NSLog(@"\n\n**************主队列同步,放到主线程会死锁***************\n\n");
// 主队列
dispatch_queue_t queue = dispatch_get_main_queue();
//同步执行
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"主队列同步1 %@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"主队列同步2 %@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"主队列同步3 %@",[NSThread currentThread]);
}
});
}
/** 主队列异步 */
- (void)asyncMain {
NSLog(@"\n\n**************主队列异步***************\n\n");
// 主队列
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"主队列异步1 %@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"主队列异步2 %@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"主队列异步3 %@",[NSThread currentThread]);
}
});
}
//输出结果为在主线程中按顺序执行
主队列异步1 {number = 1, name = main}
主队列异步1 {number = 1, name = main}
主队列异步1 {number = 1, name = main}
主队列异步2 {number = 1, name = main}
主队列异步2 {number = 1, name = main}
主队列异步2 {number = 1, name = main}
主队列异步3 {number = 1, name = main}
主队列异步3 {number = 1, name = main}
主队列异步3 {number = 1, name = main}
- (IBAction)communicationBetweenThread:(id)sender {
// 异步
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 耗时操作放在这里,例如下载图片。(运用线程休眠两秒来模拟耗时操作)
[NSThread sleepForTimeInterval:2];
NSString *picURLStr = @"http://www.bangmangxuan.net/uploads/allimg/160320/74-160320130500.jpg";
NSURL *picURL = [NSURL URLWithString:picURLStr];
NSData *picData = [NSData dataWithContentsOfURL:picURL];
UIImage *image = [UIImage imageWithData:picData];
// 回到主线程处理UI
dispatch_async(dispatch_get_main_queue(), ^{
// 在主线程上添加图片
self.imageView.image = image;
});
});
}
- (IBAction)barrierGCD:(id)sender {
// 并发队列
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
// 异步执行
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"栅栏:并发异步1 %@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"栅栏:并发异步2 %@",[NSThread currentThread]);
}
});
dispatch_barrier_async(queue, ^{
NSLog(@"------------barrier------------%@", [NSThread currentThread]);
NSLog(@"******* 并发异步执行,但是34一定在12后面 *********");
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"栅栏:并发异步3 %@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"栅栏:并发异步4 %@",[NSThread currentThread]);
}
});
}
//上面代码的打印结果如下,开启了多条线程,所有任务都是并发异步进行。但是第一组完成之后,才会进行第二组的操作。
栅栏:并发异步1 {number = 3, name = (null)}
栅栏:并发异步2 {number = 6, name = (null)}
栅栏:并发异步1 {number = 3, name = (null)}
栅栏:并发异步2 {number = 6, name = (null)}
栅栏:并发异步1 {number = 3, name = (null)}
栅栏:并发异步2 {number = 6, name = (null)}
------------barrier------------{number = 6, name = (null)}
******* 并发异步执行,但是34一定在12后面 *********
栅栏:并发异步4 {number = 3, name = (null)}
栅栏:并发异步3 {number = 6, name = (null)}
栅栏:并发异步4 {number = 3, name = (null)}
栅栏:并发异步3 {number = 6, name = (null)}
栅栏:并发异步4 {number = 3, name = (null)}
栅栏:并发异步3 {number = 6, name = (null)}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 5秒后异步执行
NSLog(@"我已经等待了5秒!");
});
GCD实现代码只执行一次
使用dispatch_once能保证某段代码在程序运行过程中只被执行1次。可以用来设计单例。
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"程序运行过程中我只执行了一次!");
});
/*!
* @brief dispatch_apply的用法
*/
- (void)dispatchApplyTest1 {
//生成全局队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
/*! dispatch_apply函数说明
*
* @brief dispatch_apply函数是dispatch_sync函数和Dispatch Group的关联API
* 该函数按指定的次数将指定的Block追加到指定的Dispatch Queue中,并等到全部的处理执行结束
*
* @param 10 指定重复次数 指定10次
* @param queue 追加对象的Dispatch Queue
* @param index 带有参数的Block, index的作用是为了按执行的顺序区分各个Block
*
*/
dispatch_apply(10, queue, ^(size_t index) {
NSLog(@"%zu", index);
});
NSLog(@"done");
/*!
* @brief 输出结果
*
2016-02-25 19:24:39.102 dispatch_apply测试[2985:165004] 0
2016-02-25 19:24:39.102 dispatch_apply测试[2985:165086] 1
2016-02-25 19:24:39.104 dispatch_apply测试[2985:165004] 4
2016-02-25 19:24:39.104 dispatch_apply测试[2985:165004] 5
2016-02-25 19:24:39.104 dispatch_apply测试[2985:165004] 6
2016-02-25 19:24:39.103 dispatch_apply测试[2985:165088] 3
2016-02-25 19:24:39.104 dispatch_apply测试[2985:165004] 7
2016-02-25 19:24:39.105 dispatch_apply测试[2985:165004] 8
2016-02-25 19:24:39.105 dispatch_apply测试[2985:165004] 9
2016-02-25 19:24:39.102 dispatch_apply测试[2985:165087] 2
2016-02-25 19:24:39.105 dispatch_apply测试[2985:165004] done
* !!!因为在Global Dispatch Queue中执行,所以各个处理的执行时间不定
但done一定会输出在最后的位置,因为dispatch_apply函数会等待所以的处理结束
*/
}
// 控制线程数量
- (void)runMaxThreadCountWithGCD
{
dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrentRunMaxThreadCountWithGCD", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t serialQueue = dispatch_queue_create("serialRunMaxThreadCountWithGCD", DISPATCH_QUEUE_SERIAL);
// 创建一个semaphore,并设置最大信号量,最大信号量表示最大线程数量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(2);
// 使用循环往串行队列 serialQueue 增加 10 个任务
for (int i = 0; i < 10 ; i++) {
dispatch_async(serialQueue, ^{
// 只有当信号量大于 0 的时候,线程将信号量减 1,程序向下执行
// 否则线程会阻塞并且一直等待,直到信号量大于 0
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_async(concurrentQueue, ^{
NSLog(@"%@ 执行任务一次 i = %d",[NSThread currentThread],i);
// 当线程任务执行完成之后,发送一个信号,增加信号量。
dispatch_semaphore_signal(semaphore);
});
});
}
NSLog(@"%@ 执行任务结束",[NSThread currentThread]);
}
//执行结果如下,只有 number 3 和 number 4 这 2 个线程在执行
<nsthread: 0x60c00007c600>{number = 1, name = main} 执行任务结束
<nsthread: 0x60c00027a340>{number = 3, name = (null)} 执行任务一次 i = 0
<nsthread: 0x608000263a00>{number = 4, name = (null)} 执行任务一次 i = 1
<nsthread: 0x60c00027a340>{number = 3, name = (null)} 执行任务一次 i = 3
<nsthread: 0x608000263a00>{number = 4, name = (null)} 执行任务一次 i = 2
<nsthread: 0x60c00027a340>{number = 3, name = (null)} 执行任务一次 i = 4
<nsthread: 0x608000263a00>{number = 4, name = (null)} 执行任务一次 i = 5
<nsthread: 0x60c00027a340>{number = 3, name = (null)} 执行任务一次 i = 6
<nsthread: 0x608000263a00>{number = 4, name = (null)} 执行任务一次 i = 7
<nsthread: 0x60c00027a340>{number = 3, name = (null)} 执行任务一次 i = 8
<nsthread: 0x608000263a00>{number = 4, name = (null)} 执行任务一次 i = 9
// 任务分组
- (void)runGroupWithGCD
{
dispatch_queue_t concurrentQueue = dispatch_queue_create("runGroupWithGCD", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < 10 ; i++) {
dispatch_group_async(group, concurrentQueue, ^{
NSLog(@"%@ 执行任务一次",[NSThread currentThread]);
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"%@ 执行任务结束",[NSThread currentThread]);
});
}
//将所有的任务都加入 group ,等待所有的任务执行完成后,dispatch_group_notify 会被调用。
<nsthread: 0x608000265180>{number = 4, name = (null)} 执行任务一次
<nsthread: 0x604000079a40>{number = 6, name = (null)} 执行任务一次
<nsthread: 0x60c000268780>{number = 5, name = (null)} 执行任务一次
<nsthread: 0x60c000267dc0>{number = 3, name = (null)} 执行任务一次
<nsthread: 0x608000265080>{number = 9, name = (null)} 执行任务一次
<nsthread: 0x600000265480>{number = 7, name = (null)} 执行任务一次
<nsthread: 0x60c00007f9c0>{number = 8, name = (null)} 执行任务一次
<nsthread: 0x608000264f40>{number = 10, name = (null)} 执行任务一次
<nsthread: 0x604000079a40>{number = 6, name = (null)} 执行任务一次
<nsthread: 0x608000265180>{number = 4, name = (null)} 执行任务一次
<nsthread: 0x60000006d180>{number = 1, name = main} 执行任务结束
队列组有下面几个特点:
// 任务分组 + 线程数量控制
- (void)runMaxCountInGroupWithGCD
{
dispatch_queue_t concurrentQueue = dispatch_queue_create("runGroupWithGCD", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_semaphore_t semaphore = dispatch_semaphore_create(2);
for (int i = 0; i < 10 ; i++) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_group_async(group, concurrentQueue, ^{
NSLog(@"%@ 执行任务一次",[NSThread currentThread]);
dispatch_semaphore_signal(semaphore);
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"%@ 执行任务结束",[NSThread currentThread]);
});
}
//执行之后,我们可以看到既控制了线程数量,也在执行任务完成之后得到了通知。
<nsthread: 0x604000269b40>{number = 3, name = (null)} 执行任务一次
<nsthread: 0x608000264780>{number = 4, name = (null)} 执行任务一次
<nsthread: 0x604000269b40>{number = 3, name = (null)} 执行任务一次
<nsthread: 0x608000264780>{number = 4, name = (null)} 执行任务一次
<nsthread: 0x608000264780>{number = 4, name = (null)} 执行任务一次
<nsthread: 0x608000264780>{number = 4, name = (null)} 执行任务一次
<nsthread: 0x604000269b40>{number = 3, name = (null)} 执行任务一次
<nsthread: 0x608000264780>{number = 4, name = (null)} 执行任务一次
<nsthread: 0x604000269b40>{number = 3, name = (null)} 执行任务一次
<nsthread: 0x60400007aa40>{number = 1, name = main} 执行任务结束
NSOperation是基于GCD之上的更高一层封装,NSOperation需要配合NSOperationQueue来实现多线程。NSOperation实现多线程的步骤如下:
1. 创建任务:先将需要执行的操作封装到NSOperation对象中。
2. 创建队列:创建NSOperationQueue。
3. 将任务加入到队列中:将NSOperation对象添加到NSOperationQueue中。
需要注意的是,NSOperation是个抽象类,实际运用时中需要使用它的子类,有三种方式:
- (void)testNSInvocationOperation {
// 创建NSInvocationOperation
NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocationOperation) object:nil];
// 开始执行操作
[invocationOperation start];
}
- (void)invocationOperation {
NSLog(@"NSInvocationOperation包含的任务,没有加入队列========%@", [NSThread currentThread]);
}
//打印结果如下,得到结论:程序在主线程执行,没有开启新线程。这是因为NSOperation多线程的使用需要配合队列NSOperationQueue,后面会讲到NSOperationQueue的使用。
NSInvocationOperation包含的任务,没有加入队列========{number = 1, name = main}
- (void)testNSBlockOperation {
// 把任务放到block中
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"NSBlockOperation包含的任务,没有加入队列========%@", [NSThread currentThread]);
}];
[blockOperation start];
}
//执行结果如下,可以看出:主线程执行,没有开启新线程。同样的,NSBlockOperation可以配合队列NSOperationQueue来实现多线程。
NSBlockOperation包含的任务,没有加入队列========{number = 1, name = main}
但是NSBlockOperation有一个方法addExecutionBlock:,通过这个方法可以让NSBlockOperation实现多线程。
- (void)testNSBlockOperationExecution {
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"NSBlockOperation运用addExecutionBlock主任务========%@", [NSThread currentThread]);
}];
[blockOperation addExecutionBlock:^{
NSLog(@"NSBlockOperation运用addExecutionBlock方法添加任务1========%@", [NSThread currentThread]);
}];
[blockOperation addExecutionBlock:^{
NSLog(@"NSBlockOperation运用addExecutionBlock方法添加任务2========%@", [NSThread currentThread]);
}];
[blockOperation addExecutionBlock:^{
NSLog(@"NSBlockOperation运用addExecutionBlock方法添加任务3========%@", [NSThread currentThread]);
}];
[blockOperation start];
}
//执行结果如下,可以看出,NSBlockOperation创建时block中的任务是在主线程执行,而运用addExecutionBlock加入的任务是在子线程执行的。
NSBlockOperation运用addExecutionBlock========{number = 1, name = main}
addExecutionBlock方法添加任务1========{number = 3, name = (null)}
addExecutionBlock方法添加任务3========{number = 5, name = (null)}
addExecutionBlock方法添加任务2========{number = 4, name = (null)}
/*******************"WHOperation.h"*************************/
#import @interface WHOperation : NSOperation
@end
/*******************"WHOperation.m"*************************/
#import "WHOperation.h"
@implementation WHOperation
- (void)main {
for (int i = 0; i < 3; i++) {
NSLog(@"NSOperation的子类WHOperation======%@",[NSThread currentThread]);
}
}
@end
/*****************回到主控制器使用WHOperation**********************/
- (void)testWHOperation {
WHOperation *operation = [[WHOperation alloc] init];
[operation start];
}
//输出结果
SOperation的子类WHOperation======{number = 1, name = main}
NSOperation的子类WHOperation======{number = 1, name = main}
NSOperation的子类WHOperation======{number = 1, name = main}
NSOperationQueue只有两种队列:主队列、其他队列。其他队列包含了串行和并发。
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
注意:
No.4:NSOperation + NSOperationQueue
把任务加入队列,这才是NSOperation的常规使用方式。
- (void)testOperationQueue {
// 创建队列,默认并发
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 创建操作,NSInvocationOperation
NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocationOperationAddOperation) object:nil];
// 创建操作,NSBlockOperation
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i < 3; i++) {
NSLog(@"addOperation把任务添加到队列======%@", [NSThread currentThread]);
}
}];
[queue addOperation:invocationOperation];
[queue addOperation:blockOperation];
}
- (void)invocationOperationAddOperation {
NSLog(@"invocationOperation===aaddOperation把任务添加到队列====%@", [NSThread currentThread]);
}
//运行结果如下,可以看出,任务都是在子线程执行的,开启了新线程!
invocationOperation===addOperation把任务添加到队列===={number = 4, name = (null)}
addOperation把任务添加到队列======{number = 3, name = (null)}
addOperation把任务添加到队列======{number = 3, name = (null)}
addOperation把任务添加到队列======{number = 3, name = (null)}
- (void)testAddOperationWithBlock {
// 创建队列,默认并发
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 添加操作到队列
[queue addOperationWithBlock:^{
for (int i = 0; i < 3; i++) {
NSLog(@"addOperationWithBlock把任务添加到队列======%@", [NSThread currentThread]);
}
}];
}
//运行结果如下,任务确实是在子线程中执行。
addOperationWithBlock把任务添加到队列======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列======{number = 3, name = (null)}
- (void)testMaxConcurrentOperationCount {
// 创建队列,默认并发
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 最大并发数为1,串行
queue.maxConcurrentOperationCount = 1;
// 最大并发数为2,并发
// queue.maxConcurrentOperationCount = 2;
// 添加操作到队列
[queue addOperationWithBlock:^{
for (int i = 0; i < 3; i++) {
NSLog(@"addOperationWithBlock把任务添加到队列1======%@", [NSThread currentThread]);
}
}];
// 添加操作到队列
[queue addOperationWithBlock:^{
for (int i = 0; i < 3; i++) {
NSLog(@"addOperationWithBlock把任务添加到队列2======%@", [NSThread currentThread]);
}
}];
// 添加操作到队列
[queue addOperationWithBlock:^{
for (int i = 0; i < 3; i++) {
NSLog(@"addOperationWithBlock把任务添加到队列3======%@", [NSThread currentThread]);
}
}];
}
//运行结果如下,当最大并发数为1的时候,虽然开启了线程,但是任务是顺序执行的,所以实现了串行。
//你可以尝试把上面的最大并发数变为2,会发现任务就变成了并发执行。
addOperationWithBlock把任务添加到队列1======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列1======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列1======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列2======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列2======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列2======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列3======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列3======{number = 3, name = (null)}
addOperationWithBlock把任务添加到队列3======{number = 3, name = (null)}
- (void)cancelAllOperations
- (void)cancel
// 暂停队列
[queue setSuspended:YES];
- (BOOL)isSuspended
暂停和取消不是立刻取消当前操作,而是等当前的操作执行完之后不再进行新的操作。
NSOperation有一个非常好用的方法,就是操作依赖。可以从字面意思理解:某一个操作(operation2)依赖于另一个操作(operation1),只有当operation1执行完毕,才能执行operation2,这时,就是操作依赖大显身手的时候了。
- (void)testAddDependency {
// 并发队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 操作1
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i < 3; i++) {
NSLog(@"operation1======%@", [NSThread currentThread]);
}
}];
// 操作2
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"****operation2依赖于operation1,只有当operation1执行完毕,operation2才会执行****");
for (int i = 0; i < 3; i++) {
NSLog(@"operation2======%@", [NSThread currentThread]);
}
}];
// 使操作2依赖于操作1
[operation2 addDependency:operation1];
// 把操作加入队列
[queue addOperation:operation1];
[queue addOperation:operation2];
}
//运行结果如下,操作2总是在操作1之后执行,成功验证了上面的说法。
operation1======{number = 3, name = (null)}
operation1======{number = 3, name = (null)}
operation1======{number = 3, name = (null)}
****operation2依赖于operation1,只有当operation1执行完毕,operation2才会执行****
operation2======{number = 4, name = (null)}
operation2======{number = 4, name = (null)}
operation2======{number = 4, name = (null)}