//
// ViewController.m
// UI-NO-25
//
// Created by Bruce on 15/8/27.
// Copyright (c) 2015年 Bruce. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 不能直接使用Operation 是因为 它里面 没有可以直接操作的方法 只是一个基类(抽象类)
NSInvocationOperation *invocation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(act:) object:@"invocation"];
// 如果单独使用Operation 必须手动启动
// [invocation start];
// Operation 默认在当前线程 去执行(同步执行)
NSInvocationOperation *invocation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(act:) object:@"invocation1"];
// 如果单独使用Operation 必须手动启动
NSInvocationOperation *invocation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(act:) object:@"invocation2"];
NSInvocationOperation *invocation3 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(act:) object:@"invocation3"];
NSInvocationOperation *invocation4 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(act:) object:@"invocation4"];
// *****NSOperationQueue不用手动去启动线程 所以注释掉start
// [invocation1 start];
// Operation 默认在当前线程 去执行(同步执行)
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
// 具体执行的方法
[self act:@"blockOperation"];
}];
// 添加操作
// NSBlockOperation 的操作数大于1的时候 会开辟线程执行
[blockOperation addExecutionBlock:^{
[self act:@"blockOperation2"];
}];
// [blockOperation start];
// Operation 默认在当前线程 去执行(同步执行)
// NSOperationQueue(线程队列) 管理线程 (默认会开辟线程去执行)
// *****NSOperationQueue不用手动去启动线程
// 异步执行
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
// 设置 线程队列的 最大并发数 (最多可以允许几个操作 同时执行)
queue.maxConcurrentOperationCount = 1;
[queue addOperation:invocation];
[queue addOperation:invocation1];
[queue addOperation:invocation2];
[queue addOperation:invocation3];
[queue addOperation:invocation4];
[queue addOperation:blockOperation];
}
- (void)act:(id)sender
{
NSLog(@"%@ %@",[NSThread currentThread],sender);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end