• 多线程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
  • 相关阅读:
    java入门最好的一套书
    【转载】vim的E492错误
    SESSION保存到数据库中,然后从数据库中读取
    django教程
    用vim写python代码的两个关键设置
    HTTP/1.1中文版
    SQL基础教程
    简单清晰的HTML教程
    vim中如何按一个键就保存文件
    【转载】Vim操作
  • 原文地址:https://www.cnblogs.com/chillytao-suiyuan/p/4834130.html
Copyright © 2020-2023  润新知