美文网首页iOS多线程iOS 多线程
iOS--多线程NSOperationQueue

iOS--多线程NSOperationQueue

作者: STONEsh | 来源:发表于2016-02-28 15:38 被阅读54次

    ViewController.m#

    //
    //  ViewController.m
    //  多线程NSOperationQueue
    //
    
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
    //---------------------- NSOperationQueue 1 -----------------------
     /*
    //1.创建线程队列(线程池)
        
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        
        //会开启一个多线程,调用block
        
        [queue addOperationWithBlock:^{
            
            for (int i = 0; i < 50; i ++) {
                NSLog(@"子线程:%d", i);
            }
            
        }];
        
    //主线程
        for (int i = 0; i < 50; i ++) {
            NSLog(@"主线程:%d", i);
        }
        
    
    */
    //---------------------- NSOperationQueue 2 -----------------------
        
    
    //1.创建线程队列(线程池)
        
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        
    //2.设置线程池最大并发数
        
        queue.maxConcurrentOperationCount = 1;
        
    //3.创建2个线程
        
        NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1) object:nil];
        
        NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread2) object:nil];
    //设置优先级
        
        [operation1 setQueuePriority:NSOperationQueuePriorityVeryLow];//operation1最后执行
        
    //4.将线程添加到线程池里
        
        [queue addOperation:operation1];
        [queue addOperation:operation2];
     
    // //主线程
        for (int i = 0; i < 300; i ++) {
            NSLog(@"主线程:%d", i);
        }
    
    
    
    
    }
        
    
        
        
        
        
        
    -(void)thread1 {
        for (int i = 0; i < 50; i++) {
            NSLog(@"thread1:%d",i);
        }
        
    }
    
    
    -(void)thread2 {
        for (int i = 0; i < 50; i++) {
            NSLog(@"thread2:%d",i);
        }
        
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
    
    

    相关文章

      网友评论

        本文标题:iOS--多线程NSOperationQueue

        本文链接:https://www.haomeiwen.com/subject/arijkttx.html