多線程之NSOpertionQueue操作隊列,nsoperationqueue

來源:互聯網
上載者:User

多線程之NSOpertionQueue操作隊列,nsoperationqueue

//NSOpertionQueue   NSOperation    //Queue    //主隊列 和 自訂隊列    //主隊列是運行在主線程當中,自訂隊列運行在後台    //NSOperation  定義需要執行的操作(任務)    //定義需要的操作,然後把該操作添加到合適的隊列中    //三個步驟    //1.建立隊列對象    //2.建立操作對象    //3.把操作對象添加到隊列之中,等待隊列分配線程執行操作    //1.建立隊列    NSOperationQueue *queue = [[NSOperationQueue alloc] init];    //設定最大並行作業數    //隊列中最多有幾個操作同時執行    queue.maxConcurrentOperationCount = 1;    //是否暫停執行隊列中的線程    [queue setSuspended:YES];    //2.建立操作    //NSOperation 不能直接使用    //使用子類的對象  兩種方式1、直接建立 2、使用block建立    NSOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self                                                            selector:@selector(thread1:)                                                              object:@"op1 "];       NSOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self                                                            selector:@selector(thread2:)                                                              object:@"op2 "];    /*    NSBlockOperation *op3 = [[NSBlockOperation alloc] init];    [op3 addExecutionBlock:^{        //具體要執行的操作    }];     */    //3.把操作加入到隊列中    [queue addOperation:op1];    [queue addOperation:op2];    //加入之後,如果有操作,那隊列就會自動執行    //4.設定作業的優先順序    [op1 setQueuePriority:NSOperationQueuePriorityLow];    [op2 setQueuePriority:NSOperationQueuePriorityVeryHigh];    //5.設定作業之間的依賴關係    [op2 addDependency:op1];    //op2的執行依賴於op1,保證op1肯定op2之前執行    //是否重新讓隊列執行    [queue setSuspended:NO];      //回到主線程列印輸出    for (int i = 0; i < 50; i ++) {        NSLog(@"主線程 : %d", i);    }}- (void)thread1:(NSString *)name{    //具體要執行的操作    for (int i = 0; i < 50; i ++) {        NSLog(@"多線程 %@:     %d", name, i);    }}- (void)thread2:(NSString *)name{    for (int i = 0; i < 50; i ++) {        NSLog(@"多線程 %@:     %d", name, i);    }}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.