zoukankan      html  css  js  c++  java
  • 多线程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
  • 相关阅读:
    《数据密集型应用系统设计》读书笔记
    每周总结
    每周总结
    每周总结
    《数据密集型应用系统设计》读书笔记
    每周总结
    《重构》读书笔记
    每周总结
    软件过程与管理知识回顾
    操作系统知识汇总5-6章
  • 原文地址:https://www.cnblogs.com/chillytao-suiyuan/p/4834130.html
Copyright © 2011-2022 走看看