#import <UIKit/UIKit.h> @interface VCRoot : UIViewController @end #import "VCRoot.h" @interface VCRoot () @property (assign,atomic) int count ; @end @implementation VCRoot { //任务队列 //能够将任务(线程的抽象)添加到队列中来管理 //能够同时并发多个任务 NSOperationQueue* _optQueue ; NSData* data ; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. //建立一个任务队列 //队列中的元素为任务对象 //任务对象继承于NSOperation _optQueue = [[NSOperationQueue alloc] init] ; //设置任务的最大并发数量 [_optQueue setMaxConcurrentOperationCount:5] ; } -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //建立一个任务对象 //将事件函数封装到任务中 //未来在队列中执行 NSInvocationOperation* tast01 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(updateOpt01) object:nil] ; //将任务添加到队列中 [_optQueue addOperation:tast01] ; //方法二 //建立一个任务属性对象 NSInvocation* invo = [[NSInvocation alloc] init] ; //目标对象 invo.target = self ; //事件函数 invo.selector = @selector(updateOpt02) ; NSInvocationOperation* tast02 = [[NSInvocationOperation alloc] initWithInvocation:invo] ; //将第二个任务添加到队列中 [_optQueue addOperation:tast02] ; //方法三 NSMutableArray* arrayTask = [[NSMutableArray alloc] init] ; for (int i = 0 ; i < 3; i++) { //建立多个任务,将任务添加到数组中 NSInvocationOperation* task = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(updateOpt) object:nil] ; [arrayTask addObject:task] ; } //将任务数组添加到任务队列中 //是否等待以前的任务结束后开始执行 [_optQueue addOperations:arrayTask waitUntilFinished:YES] ; // 第四种方法,使用block来添加任务 // 添加一个block块对象做为任务队列的任务 [_optQueue addOperationWithBlock:^ { int count = 0 ; for (int i = 0 ; i < 10000; i++) { count++ ; NSLog(@"count = %d",count) ; } }] ; } -(void) readFile { data = [NSData dataWithContentsOfFile:@"/users/qianfeng/Desktop/office.zip"] ; } -(void) updateOpt01 { NSLog(@"任务一执行...."); [data writeToFile:@"/users/qianfeng/Desktop/office01.zip" atomically:YES] ; // [NSThread exit] ; NSThread* t = [NSThread currentThread] ; [t cancel] ; while (true) { //休眠时间 [NSThread sleepForTimeInterval:0.01] ; NSLock* lock = [[NSLock alloc] init] ; int k = 0 ; [lock lock] ; k++ ; [lock unlock] ; [NSThread isMainThread] ; } } -(void) updateOpt11 { NSLog(@"任务一执行...."); [data writeToFile:@"/users/qianfeng/Desktop/office02.zip" atomically:YES] ; } -(void) updateOpt12 { NSLog(@"任务一执行...."); [data writeToFile:@"/users/qianfeng/Desktop/office03.zip" atomically:YES] ; } -(void) updateOpt02 { NSLog(@"任务二执行..."); } -(void) updateOpt { NSLog(@"任务数组中的任务执行!"); [NSThread sleepForTimeInterval:5]; } @end