iOS多線程——NSOperation相關 一、簡介 二、基礎 三、使用NSOperation、NSOperationQueue 四、總結

一、簡介

        NSOperation、NSOperationQueue 是蘋果對GCD進行面向對象的封裝。雖然GCD已經很好用了,但是也是不可能適用於所有場景的;GCD比較簡單,其適用於比較簡單的場景——後臺執行一個任務,然後再返回到主線程之類。如果是複雜的業務場景(任務之間的關係複雜),GCD就不適用。相對於GCD,那麼NSOperation、NSOperationQueue有哪些優勢?

  1. 可添加完成的代碼塊,在操作完成後執行(GCD不能方便的完成,只能用任務中的任務來實現,不方便)
  2. 添加操作之間的依賴關係,方便的控制執行順序(GCD中可以使用agroup、柵欄來完成,不方便)
  3. 設定操作執行的優先級(一定程度上可以設置隊列的優先級來模擬)
  4. 可以很方便的取消一個操作的執行(GCD不能取消)
  5. 使用 KVO 觀察對操作執行狀態的更改:isExecuteing、isFinished、isCancelled(GCD不能查看任務狀態)

二、基礎

  1. 操作(NSOperation,與GCD中的任務對應)
  • 就是我們想執行的那段代碼
  • 在 NSOperation 中,我們使用 NSOperation 子類 NSInvocationOperation、NSBlockOperation,或者自定義子類來封裝操作
  1. 操作隊列(NSOperationQueue,與GCD中的隊列對應)
  • 用來存放操作的隊列
  • 不同於 GCD 中的調度隊列 FIFO(先進先出)的原則
    • NSOperationQueue 對於添加到隊列中的操作,首先進入準備就緒的狀態(就緒狀態取決於操作之間的依賴關係)
    • 然後進入就緒狀態的操作的開始執行順序(非結束執行順序)由操作之間相對的優先級決定(優先級是操作對象自身的屬性)
    • 操作隊列通過設置最大併發操作數(maxConcurrentOperationCount)來控制併發、串行
    • NSOperationQueue 爲我們提供了兩種不同類型的隊列:主隊列和自定義隊列;主隊列運行在主線程之上,而自定義隊列在後臺執行

三、使用NSOperation、NSOperationQueue

3.1 概述

        NSOperation需要配合NSOperationQueue來實現多線程。因爲默認情況下,NSOperation 單獨使用時系統同步執行操作,配合 NSOperationQueue 我們能更好的實現異步執行。NSOperation 實現多線程的使用步驟分爲三步:

  1. 創建操作:先將需要執行的操作封裝到一個 NSOperation 對象中。
  • 使用子類 NSInvocationOperation
  • 使用子類 NSBlockOperation
  • 自定義繼承自 NSOperation 的子類,通過實現內部相應的方法來封裝操作。
  1. 創建隊列:創建 NSOperationQueue 對象。
  2. 將操作加入到隊列中:將 NSOperation 對象添加到 NSOperationQueue 對象中。
            之後呢,系統就會自動將 NSOperationQueue 中的 NSOperation 取出來,在新線程中執行操作。

3.2 使用NSOperation

// 使用NSInvocationOperation;單獨使用NSInvocationOperation時,在當前線程執行操作
- (void)useInvocation {
    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocat) object:nil];
    [op start];
}

- (void)invocat {
    NSLog(@"invocat %@", [NSThread currentThread]);
}

// 使用子類 NSBlockOperation;單獨使用NSBlockOperation時,在當前線程執行操作
- (void)useBlockOperation {
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"1---%@", [NSThread currentThread]); // 打印當前線程
        }
    }];

    [op start];
}

// 使用子類 NSBlockOperation;單獨添加的addExecutionBlock,在其他線程執行操作
- (void)useBlockOperationAddExecutionBlock {

    // 1.創建 NSBlockOperation 對象
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"1---%@", [NSThread currentThread]); // 打印當前線程
        }
    }];

    // 2.添加額外的操作
    [op addExecutionBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"2---%@", [NSThread currentThread]); // 打印當前線程
        }
    }];
    [op addExecutionBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"3---%@", [NSThread currentThread]); // 打印當前線程
        }
    }];

    // 3.調用 start 方法開始執行操作
    [op start];
}

輸出
2021-09-01 08:58:39.350611+0800 ios-oc[89571:1133998] 3---<NSThread: 0x600000558880>{number = 7, name = (null)}
2021-09-01 08:58:39.350611+0800 ios-oc[89571:1134006] 1---<NSThread: 0x600000521080>{number = 9, name = (null)}
2021-09-01 08:58:39.350611+0800 ios-oc[89571:1133997] 2---<NSThread: 0x60000052c740>{number = 6, name = (null)}
2021-09-01 08:58:41.354755+0800 ios-oc[89571:1133997] 2---<NSThread: 0x60000052c740>{number = 6, name = (null)}
2021-09-01 08:58:41.354754+0800 ios-oc[89571:1133998] 3---<NSThread: 0x600000558880>{number = 7, name = (null)}
2021-09-01 08:58:41.354760+0800 ios-oc[89571:1134006] 1---<NSThread: 0x600000521080>{number = 9, name = (null)}
2021-09-01 08:58:41.355033+0800 ios-oc[89571:1134006] viewDidLoad <NSThread: 0x600000521080>{number = 9, name = (null)}

// 如果添加的操作多的話,blockOperationWithBlock: 中的操作也可能會在其他線程(非當前線程)中執行
// 這是由系統決定的,並不是說添加到 blockOperationWithBlock: 中的操作一定會在當前線程中執行。


// 使用自定義繼承自 NSOperation 的子類
// 可以通過重寫 main 或者 start 方法 來定義自己的 NSOperation 對象
// 重寫main方法比較簡單,我們不需要管理操作的狀態屬性 isExecuting 和 isFinished
// 當 main 執行完返回的時候,這個操作就結束了
@interface CusOperation : NSOperation
@end

@implementation CusOperation
- (void)main {
    if (!self.isCancelled) {
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2];
            NSLog(@"1---%@", [NSThread currentThread]);
        }
    }
}
@end

- (void)useCustomOp {
    CusOperation *op = [[CusOperation alloc] init];
    [op start];
}

3.3 使用NSOperationQueue

  1. 主隊列:凡是添加到主隊列中的操作,都會放到主線程中執行。
// 主隊列獲取方法
NSOperationQueue *queue = [NSOperationQueue mainQueue];
  1. 自定義隊列(非主隊列;添加到這種隊列中的操作,就會自動放到子線程中執行)
// 自定義隊列創建方法;同時包含了:串行、併發功能
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  1. 使用NSOperationQueue
/*--------------使用隊列--------------------*/
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [NSThread detachNewThreadWithBlock:^{
            _operation = [[MyOperation alloc] init];
            [_operation addOperationToQueue];
            
            NSLog(@"viewDidLoad %@", [NSThread currentThread]);
    }];
}

- (void)addOperationToQueue {

    // 1.創建隊列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    // 2.創建操作
    // 使用 NSInvocationOperation 創建操作1
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocat) object:nil];

    // 使用 NSInvocationOperation 創建操作2
    NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocat) object:nil];

    // 使用 NSBlockOperation 創建操作3
    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"3---%@", [NSThread currentThread]); // 打印當前線程
        }
    }];
    [op3 addExecutionBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"4---%@", [NSThread currentThread]); // 打印當前線程
        }
    }];

    // 3.使用 addOperation: 添加所有操作到隊列中
    [queue addOperation:op1]; // [op1 start]
    [queue addOperation:op2]; // [op2 start]
    [queue addOperation:op3]; // [op3 start]
}

2021-09-01 09:30:26.575273+0800 ios-oc[90558:1160132] invocat <NSThread: 0x60000328cc80>{number = 6, name = (null)}
2021-09-01 09:30:26.575273+0800 ios-oc[90558:1160133] invocat <NSThread: 0x600003295d00>{number = 7, name = (null)}
2021-09-01 09:30:26.575296+0800 ios-oc[90558:1160141] viewDidLoad <NSThread: 0x60000328c900>{number = 8, name = (null)}
2021-09-01 09:30:28.576771+0800 ios-oc[90558:1160134] 3---<NSThread: 0x6000032c4940>{number = 5, name = (null)}
2021-09-01 09:30:28.576771+0800 ios-oc[90558:1160138] 4---<NSThread: 0x6000032c8a40>{number = 3, name = (null)}
2021-09-01 09:30:30.576893+0800 ios-oc[90558:1160138] 4---<NSThread: 0x6000032c8a40>{number = 3, name = (null)}
2021-09-01 09:30:30.576897+0800 ios-oc[90558:1160134] 3---<NSThread: 0x6000032c4940>{number = 5, name = (null)}

// 可以看出添加到NSOperationQueue的隊列在多個線程上運行

  1. 使用NSOperationQueue控制鬢髮與串行
            之前我們說過,NSOperationQueue 創建的自定義隊列同時具有串行、併發功能,上邊我們演示了併發功能,那麼他的串行功能是如何實現的?這裏有個關鍵屬性 maxConcurrentOperationCount,叫做最大併發操作數。用來控制一個特定隊列中可以有多少個操作同時參與併發執行。
            最大併發操作數:maxConcurrentOperationCount
  • maxConcurrentOperationCount 默認情況下爲-1,表示不進行限制,可進行併發執行。
  • maxConcurrentOperationCount 爲1時,隊列爲串行隊列。只能串行執行。
  • maxConcurrentOperationCount 大於1時,隊列爲併發隊列。操作併發執行,當然這個值不應超過系統限制,即使自己設置一個很大的值,系統也會自動調整爲 min{自己設定的值,系統設定的默認最大值}。

注意:這裏 maxConcurrentOperationCount 控制的不是併發線程的數量,而是一個隊列中同時能併發執行的最大操作數。而且一個操作也並非只能在一個線程中運行。

// 在3. 使用NSOperationQueue中,添加如下代碼
queue.maxConcurrentOperationCount = 1;

// 輸出結果是:可以看出任務是串行執行的,但是不一定都是在一個線程上執行的;同時任務的順序也不保證
2021-09-01 09:40:32.257253+0800 ios-oc[90871:1168825] viewDidLoad <NSThread: 0x600002912c40>{number = 6, name = (null)}
2021-09-01 09:40:32.257255+0800 ios-oc[90871:1168822] invocat <NSThread: 0x600002944240>{number = 3, name = (null)}
2021-09-01 09:40:32.257444+0800 ios-oc[90871:1168821] invocat <NSThread: 0x60000291acc0>{number = 4, name = (null)}
2021-09-01 09:40:34.262638+0800 ios-oc[90871:1168821] 3---<NSThread: 0x60000291acc0>{number = 4, name = (null)}
2021-09-01 09:40:34.262638+0800 ios-oc[90871:1168822] 4---<NSThread: 0x600002944240>{number = 3, name = (null)}
2021-09-01 09:40:36.266506+0800 ios-oc[90871:1168821] 3---<NSThread: 0x60000291acc0>{number = 4, name = (null)}
2021-09-01 09:40:36.266506+0800 ios-oc[90871:1168822] 4---<NSThread: 0x600002944240>{number = 3, name = (null)}
  1. NSOperation 操作依賴
            NSOperation能添加操作之間的依賴關係。通過操作依賴,可以很方便的控制操作之間的執行順序,其提供了3個接口供我們管理和查看依賴。
  • (void)addDependency:(NSOperation *)op; 添加依賴,使當前操作依賴於操作 op 的完成。
  • (void)removeDependency:(NSOperation *)op; 移除依賴,取消當前操作對操作 op 的依賴。
  • @property (readonly, copy) NSArray<NSOperation *> *dependencies; 在當前操作開始執行之前完成執行的所有操作對象數組
- (void)addDependency {

    // 1.創建隊列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    // 2.創建操作
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"1---%@", [NSThread currentThread]); // 打印當前線程
        }
    }];
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"2---%@", [NSThread currentThread]); // 打印當前線程
        }
    }];

    // 3.添加依賴
    [op2 addDependency:op1]; // 讓op2 依賴於 op1,則先執行op1,在執行op2

    // 4.添加操作到隊列中
    [queue addOperation:op1];
    [queue addOperation:op2];
}

2021-09-01 09:50:53.197749+0800 ios-oc[91179:1178682] 1---<NSThread: 0x600002b00140>{number = 5, name = (null)}
2021-09-01 09:50:55.201917+0800 ios-oc[91179:1178682] 1---<NSThread: 0x600002b00140>{number = 5, name = (null)}
2021-09-01 09:50:57.207503+0800 ios-oc[91179:1178680] 2---<NSThread: 0x600002b12240>{number = 8, name = (null)}
2021-09-01 09:50:59.210177+0800 ios-oc[91179:1178680] 2---<NSThread: 0x600002b12240>{number = 8, name = (null)}
  1. NSOperation優先級
            NSOperation 提供了queuePriority(優先級)屬性,queuePriority屬性適用於同一操作隊列中的操作,不適用於不同操作隊列中的操作。默認情況下,所有新創建的操作對象優先級都是NSOperationQueuePriorityNormal。但是我們可以通過setQueuePriority:方法來改變當前操作在同一隊列中的執行優先級。
// 優先級的取值
typedef NS_ENUM(NSInteger, NSOperationQueuePriority) {
    NSOperationQueuePriorityVeryLow = -8L,
    NSOperationQueuePriorityLow = -4L,
    NSOperationQueuePriorityNormal = 0,
    NSOperationQueuePriorityHigh = 4,
    NSOperationQueuePriorityVeryHigh = 8
};

        上邊我們說過:對於添加到隊列中的操作,首先進入準備就緒的狀態(就緒狀態取決於操作之間的依賴關係),然後進入就緒狀態的操作的開始執行順序(非結束執行順序)由操作之間相對的優先級決定(優先級是操作對象自身的屬性)。
        那麼,什麼樣的操作纔是進入就緒狀態的操作呢?
        當一個操作的所有依賴都已經完成時,操作對象通常會進入準備就緒狀態,等待執行。舉個例子,現在有4個優先級都是 NSOperationQueuePriorityNormal(默認級別)的操作:op1,op2,op3,op4。其中 op3 依賴於 op2,op2 依賴於 op1,即 op3 -> op2 -> op1。現在將這4個操作添加到隊列中併發執行。
        因爲 op1 和 op4 都沒有需要依賴的操作,所以在 op1,op4 執行之前,就是出於準備就緒狀態的操作。而 op3 和 op2 都有依賴的操作(op3 依賴於 op2,op2 依賴於 op1),所以 op3 和 op2 都不是準備就緒狀態下的操作。理解了進入就緒狀態的操作,那麼我們就理解了queuePriority 屬性的作用對象。queuePriority 屬性決定了進入準備就緒狀態下的操作之間的開始執行順序。並且,優先級不能取代依賴關係。如果一個隊列中既包含高優先級操作,又包含低優先級操作,並且兩個操作都已經準備就緒,那麼隊列先執行高優先級操作。比如上例中,如果 op1 和 op4 是不同優先級的操作,那麼就會先執行優先級高的操作。如果,一個隊列中既包含了準備就緒狀態的操作,又包含了未準備就緒的操作,未準備就緒的操作優先級比準備就緒的操作優先級高。那麼,雖然準備就緒的操作優先級低,也會優先執行。優先級不能取代依賴關係。如果要控制操作間的啓動順序,則必須使用依賴關係。

  1. 回到主線程
- (void)communication {

    // 1.創建隊列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    // 2.添加操作
    [queue addOperationWithBlock:^{
        // 異步進行耗時操作
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
            NSLog(@"1---%@", [NSThread currentThread]); // 打印當前線程
        }

        // 回到主線程
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            // 進行一些 UI 刷新等操作
            for (int i = 0; i < 2; i++) {
                [NSThread sleepForTimeInterval:2]; // 模擬耗時操作
                NSLog(@"2---%@", [NSThread currentThread]); // 打印當前線程
            }
        }];
    }];
}
  1. 線程安全與同步(NSOperationQueue不是線程安全的)
/**
 * 非線程安全:不使用 NSLock
 * 初始化火車票數量、賣票窗口(非線程安全)、並開始賣票
 */
- (void)initTicketStatusNotSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印當前線程

    self.ticketSurplusCount = 50;

    // 1.創建 queue1,queue1 代表北京火車票售賣窗口
    NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
    queue1.maxConcurrentOperationCount = 1;

    // 2.創建 queue2,queue2 代表上海火車票售賣窗口
    NSOperationQueue *queue2 = [[NSOperationQueue alloc] init];
    queue2.maxConcurrentOperationCount = 1;

    // 3.創建賣票操作 op1
    __weak typeof(self) weakSelf = self;
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf saleTicketNotSafe];
    }];

    // 4.創建賣票操作 op2
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf saleTicketNotSafe];
    }];

    // 5.添加操作,開始賣票
    [queue1 addOperation:op1];
    [queue2 addOperation:op2];
}

/**
 * 售賣火車票(非線程安全)
 */
- (void)saleTicketNotSafe {
    while (1) {

        if (self.ticketSurplusCount > 0) {
            //如果還有票,繼續售賣
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩餘票數:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else {
            NSLog(@"所有火車票均已售完");
            break;
        }
    }
}

2021-09-01 10:01:21.679827+0800 ios-oc[91539:1188684] 剩餘票數:49 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:21.679830+0800 ios-oc[91539:1188689] 剩餘票數:48 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:21.882894+0800 ios-oc[91539:1188689] 剩餘票數:47 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:21.882903+0800 ios-oc[91539:1188684] 剩餘票數:47 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:22.083785+0800 ios-oc[91539:1188684] 剩餘票數:46 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:22.083785+0800 ios-oc[91539:1188689] 剩餘票數:46 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:22.284927+0800 ios-oc[91539:1188684] 剩餘票數:45 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:22.284942+0800 ios-oc[91539:1188689] 剩餘票數:44 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:22.488073+0800 ios-oc[91539:1188684] 剩餘票數:42 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:22.488071+0800 ios-oc[91539:1188689] 剩餘票數:43 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:22.691948+0800 ios-oc[91539:1188684] 剩餘票數:41 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:22.692000+0800 ios-oc[91539:1188689] 剩餘票數:40 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:22.892420+0800 ios-oc[91539:1188684] 剩餘票數:39 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:22.892420+0800 ios-oc[91539:1188689] 剩餘票數:38 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:23.094124+0800 ios-oc[91539:1188689] 剩餘票數:37 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:23.094124+0800 ios-oc[91539:1188684] 剩餘票數:37 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:23.299441+0800 ios-oc[91539:1188689] 剩餘票數:36 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:23.299441+0800 ios-oc[91539:1188684] 剩餘票數:35 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:23.500354+0800 ios-oc[91539:1188684] 剩餘票數:34 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:23.500355+0800 ios-oc[91539:1188689] 剩餘票數:34 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:23.705105+0800 ios-oc[91539:1188684] 剩餘票數:33 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:23.705105+0800 ios-oc[91539:1188689] 剩餘票數:32 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:23.908486+0800 ios-oc[91539:1188689] 剩餘票數:30 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:23.908469+0800 ios-oc[91539:1188684] 剩餘票數:31 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:24.113731+0800 ios-oc[91539:1188689] 剩餘票數:29 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:24.113753+0800 ios-oc[91539:1188684] 剩餘票數:28 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:24.317027+0800 ios-oc[91539:1188689] 剩餘票數:27 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:24.317027+0800 ios-oc[91539:1188684] 剩餘票數:27 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:24.517591+0800 ios-oc[91539:1188684] 剩餘票數:26 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:24.517656+0800 ios-oc[91539:1188689] 剩餘票數:26 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:24.723093+0800 ios-oc[91539:1188684] 剩餘票數:25 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:24.723093+0800 ios-oc[91539:1188689] 剩餘票數:25 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:24.928560+0800 ios-oc[91539:1188684] 剩餘票數:24 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:24.928586+0800 ios-oc[91539:1188689] 剩餘票數:23 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:25.133712+0800 ios-oc[91539:1188684] 剩餘票數:22 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:25.133710+0800 ios-oc[91539:1188689] 剩餘票數:21 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:25.337721+0800 ios-oc[91539:1188684] 剩餘票數:20 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:25.337744+0800 ios-oc[91539:1188689] 剩餘票數:19 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:25.542036+0800 ios-oc[91539:1188684] 剩餘票數:18 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:25.542036+0800 ios-oc[91539:1188689] 剩餘票數:17 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:25.744927+0800 ios-oc[91539:1188684] 剩餘票數:16 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:25.744926+0800 ios-oc[91539:1188689] 剩餘票數:16 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:25.950355+0800 ios-oc[91539:1188689] 剩餘票數:14 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:25.950354+0800 ios-oc[91539:1188684] 剩餘票數:15 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:26.150979+0800 ios-oc[91539:1188689] 剩餘票數:13 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:26.151086+0800 ios-oc[91539:1188684] 剩餘票數:12 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:26.351582+0800 ios-oc[91539:1188684] 剩餘票數:11 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:26.351598+0800 ios-oc[91539:1188689] 剩餘票數:10 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:26.552269+0800 ios-oc[91539:1188684] 剩餘票數:8 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:26.552241+0800 ios-oc[91539:1188689] 剩餘票數:9 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:26.752944+0800 ios-oc[91539:1188684] 剩餘票數:7 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:26.752959+0800 ios-oc[91539:1188689] 剩餘票數:6 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:26.957910+0800 ios-oc[91539:1188684] 剩餘票數:5 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:26.957917+0800 ios-oc[91539:1188689] 剩餘票數:4 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:27.158551+0800 ios-oc[91539:1188684] 剩餘票數:3 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:27.158551+0800 ios-oc[91539:1188689] 剩餘票數:2 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:27.364144+0800 ios-oc[91539:1188684] 剩餘票數:0 窗口:<NSThread: 0x60000364ab00>{number = 6, name = (null)}
2021-09-01 10:01:27.364144+0800 ios-oc[91539:1188689] 剩餘票數:1 窗口:<NSThread: 0x6000036587c0>{number = 4, name = (null)}
2021-09-01 10:01:27.566469+0800 ios-oc[91539:1188684] 所有火車票均已售完
2021-09-01 10:01:27.566464+0800 ios-oc[91539:1188689] 所有火車票均已售完
// 使用NSLock對資源進行加鎖

/**
 * 線程安全:使用 NSLock 加鎖
 * 初始化火車票數量、賣票窗口(線程安全)、並開始賣票
 */

- (void)initTicketStatusSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印當前線程

    self.ticketSurplusCount = 50;

    self.lock = [[NSLock alloc] init];  // 初始化 NSLock 對象

    // 1.創建 queue1,queue1 代表北京火車票售賣窗口
    NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
    queue1.maxConcurrentOperationCount = 1;

    // 2.創建 queue2,queue2 代表上海火車票售賣窗口
    NSOperationQueue *queue2 = [[NSOperationQueue alloc] init];
    queue2.maxConcurrentOperationCount = 1;

    // 3.創建賣票操作 op1
    __weak typeof(self) weakSelf = self;
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf saleTicketSafe];
    }];

    // 4.創建賣票操作 op2
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf saleTicketSafe];
    }];

    // 5.添加操作,開始賣票
    [queue1 addOperation:op1];
    [queue2 addOperation:op2];
}

/**
 * 售賣火車票(線程安全)
 */
- (void)saleTicketSafe {
    while (1) {

        // 加鎖
        [self.lock lock];

        if (self.ticketSurplusCount > 0) {
            //如果還有票,繼續售賣
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩餘票數:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        }

        // 解鎖
        [self.lock unlock];

        if (self.ticketSurplusCount <= 0) {
            NSLog(@"所有火車票均已售完");
            break;
        }
    }
}

四、總結

4.1 NSOperation 常用屬性和方法

  1. 取消操作方法
    • - (void)cancel; 可取消操作,實質是標記 isCancelled 狀態。
  2. 判斷操作狀態方法
    • - (BOOL)isFinished; 判斷操作是否已經結束。
    • - (BOOL)isCancelled; 判斷操作是否已經標記爲取消。
    • - (BOOL)isExecuting; 判斷操作是否正在在運行。
    • - (BOOL)isReady; 判斷操作是否處於準備就緒狀態,這個值和操作的依賴關係相關。
  3. 操作同步
    • - (void)waitUntilFinished; 阻塞當前線程,直到該操作結束。可用於線程執行順序的同步。
    • - (void)setCompletionBlock:(void (^)(void))block; completionBlock 會在當前操作執行完畢時執行 completionBlock。
    • - (void)addDependency:(NSOperation *)op; 添加依賴,使當前操作依賴於操作 op 的完成。
    • - (void)removeDependency:(NSOperation *)op; 移除依賴,取消當前操作對操作 op 的依賴。
    • @property (readonly, copy) NSArray<NSOperation *> *dependencies; 在當前操作開始執行之前完成執行的所有操作對象數組。

4.2 NSOperationQueue 常用屬性和方法

  1. 取消/暫停/恢復操作
    • - (void)cancelAllOperations; 可以取消隊列的所有操作。
    • - (BOOL)isSuspended; 判斷隊列是否處於暫停狀態。 YES 爲暫停狀態,NO 爲恢復狀態。
    • - (void)setSuspended:(BOOL)b; 可設置操作的暫停和恢復,YES 代表暫停隊列,NO 代表恢復隊列。
  2. 操作同步
    • - (void)waitUntilAllOperationsAreFinished; 阻塞當前線程,直到隊列中的操作全部執行完畢。
  3. 添加/獲取操作
    • - (void)addOperationWithBlock:(void (^)(void))block; 向隊列中添加一個 NSBlockOperation 類型操作對象。
    • - (void)addOperations:(NSArray *)ops waitUntilFinished:(BOOL)wait; 向隊列中添加操作數組,wait 標誌是否阻塞當前線程直到所有操作結束
    • - (NSArray *)operations; 當前在隊列中的操作數組(某個操作執行結束後會自動從這個數組清除)。
    • - (NSUInteger)operationCount; 當前隊列中的操作數。
  4. 獲取隊列
    • + (id)currentQueue; 獲取當前隊列,如果當前線程不是在 NSOperationQueue 上運行則返回 nil。
    • + (id)mainQueue; 獲取主隊列。

注意:

  1. 這裏的暫停和取消(包括操作的取消和隊列的取消)並不代表可以將當前的操作立即取消,而是噹噹前的操作執行完畢之後不再執行新的操作。
  2. 暫停和取消的區別就在於:暫停操作之後還可以恢復操作,繼續向下執行;而取消操作之後,所有的操作就清空了,無法再接着執行剩下的操作。

注意:非本人原創,基於https://bujige.net/blog/iOS-Complete-learning-NSOperation.html進行了部分修改

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章