多线程NSInvocationOperation(NSOperationQueue)的基本用法

 
 
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    /*---------------------------NSOperation--------------------------------------*/
    //创建线程队列(线程池)
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
   
    //关闭暂停队列
    [queue setSuspended:YES];
   
    //设置最大并发数
    queue.maxConcurrentOperationCount = 1;
   
    //创建线程
    NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1:) object:@"op1"];
    //设置线程的优先级
    operation1.queuePriority = NSOperationQueuePriorityNormal;
   
    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread2:) object:@"op2"];
    //设置优先级
    operation2.queuePriority = NSOperationQueuePriorityHigh;
   
    //将线程添加到队列中
    [queue addOperation:operation1];
    [queue addOperation:operation2];
   
    //方式二:block
    [queue addOperationWithBlock:^{
       
        @autoreleasepool {
            for (int i=0; i<50; i++) {
                NSLog(@"op3:%d",i);
            }
        }
       
    }];
   
   
    //开始队列 —在并发数为1的时候能让后加入队列的最先打印出来
    [queue setSuspended:NO];
   
}


- (void)thread1:(NSString *)threadName {

    @autoreleasepool {
        for (int i=0; i<50; i++) {
            NSLog(@"thread1:%d",i);
        }
       
    }
   
}

- (void)thread2:(NSString *)threadName {
   
    @autoreleasepool {
       
        for (int i=0; i<50; i++) {
            NSLog(@"thread2:%d",i);
        }
       
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
       
       
//        [[NSRunLoop currentRunLoop] run];
       
    }
   
}

- (void)timeAction {

    NSLog(@"timeAction");
   
}
@end
原文地址:https://www.cnblogs.com/chillytao-suiyuan/p/4834130.html