您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 多線程(二):NSThread 詳解

編輯:iOS 開發綜合

在 iOS 中,NSThread 用來代表線程,創建新線程本質上就是創建一個 NSThread 對象。

一、創建和啟動線程

iOS 10 之前提供了兩種開啟線程的方法:

- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument;
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;

第一種是實例方法,返回一個 NSThread 對象,必須調用 start 方法才能啟動線程;第二種是類方法,不返回 NSThread 對象,直接創建並啟動線程。

iOS 10 又新增了兩種基於 block 的方法:

- (instancetype)initWithBlock:(void (^)(void))block;
+ (void)detachNewThreadWithBlock:(void (^)(void))block;

這兩個方法與上述類似,也是一個實例方法、一個類方法,只是執行體改成了 block。具體用法如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeThread1beforeIOS10];
    [self makeThread2beforeIOS10];
    [self makeThread1FromIOS10];
    [self makeThread2FromIOS10];
}

- (void)run {
    for (int i = 0; i < 10; i++) {
        NSLog(@"%@,----i=%d", [NSThread currentThread], i);
        NSLog(@"isMainThread=%d", [NSThread isMainThread]);
    }
}

// iOS 10 之前:第一種,實例方法,最多傳一個參數
- (void)makeThread1beforeIOS10 {
    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [thread1 setName:@"fisrt blood"];
    [thread1 start]; // 啟動線程
}

// iOS 10 之前:第二種,類方法,最多傳一個參數
- (void)makeThread2beforeIOS10 {
    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
}

// iOS 10:第三種,實例方法(僅 iOS 10 及以上可用)
- (void)makeThread1FromIOS10 {
    NSThread *thread3 = [[NSThread alloc] initWithBlock:^{
        for (int i = 0; i < 10; i++) {
            NSLog(@"%@,第三種 i=%d", [NSThread currentThread], i);
        }
    }];
    thread3.name = @"triple kill";
    [thread3 start];
}

// iOS 10:第四種,類方法
- (void)makeThread2FromIOS10 {
    [NSThread detachNewThreadWithBlock:^{
        for (int i = 0; i < 10; i++) {
            NSLog(@"%@,第四種 i=%d", [NSThread currentThread], i);
        }
    }];
}

二、常用方法

主線程相關:

+ (NSThread *)mainThread; // 獲得主線程
- (BOOL)isMainThread;     // 是否為主線程
+ (BOOL)isMainThread;     // 是否為主線程

其他方法:

獲得當前線程:

NSThread *current = [NSThread currentThread];

線程的調度優先級(取值範圍 0.0 ~ 1.0,默認 0.5,值越大優先級越高,一般不建议修改):

+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
- (double)threadPriority;
- (BOOL)setThreadPriority:(double)p;

線程的名字:

- (void)setName:(NSString *)n;
- (NSString *)name;

三、線程的狀態

線程共有五種狀態:新建、就緒、運行、阻塞、死亡。

新建:程序建立線程後,線程進入新建狀態,此時僅由系統分配了內存並初始化了成員變量。

就緒:調用 start 方法後,線程進入就緒狀態,此時尚未運行,具體何時運行取決於系統調度。

運行:系統調度到該線程時進入運行狀態;若調用到其他線程,則重新回到就緒狀態。

阻塞:當線程調用 sleep 方法或等待同步鎖時進入阻塞狀態。

死亡:線程執行完畢或異常/強制退出後進入死亡狀態。

啟動線程:

- (void)start; // 就緒 → 運行,任務執行完畢後自動進入死亡狀態

阻塞(暫停)線程:

+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

強制停止線程:

+ (void)exit; // 進入死亡狀態,一旦停止便不能再次開啟任務

四、停止線程

線程的結束方式有三種:1)執行體方法執行完成,正常結束;2)執行過程中發生異常;3)調用 NSThread 的 exit 方法停止當前線程。由於 exit 是類方法,只能停止正在執行的線程。我們可以在主線程或其他線程中調用 [thread cancel],再由子線程在執行體中判斷是否 cancel 來停止:

if ([[NSThread currentThread] isCancelled]) {
    [NSThread exit];
}

五、多線程安全

多線程編程中必然涉及線程安全問題,比如資源共享(多個線程訪問同一對象、變量或文件),稍不注意就會出現數據錯亂。以下面經典的「取錢」問題為例:

如上圖,餘額 1500 卻被兩個線程各取出 800,最終還剩 700,這顯然不合理。

- (void)takeMoney:(NSNumber *)count {
    [_account take:count.doubleValue];
}

- (IBAction)actionTest:(id)sender {
    _account = [[ZPYAccount alloc] initWithCardId:@"1234567" andBalance:1500];
    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(takeMoney:) object:@800];
    [thread1 setName:@"first thread"];
    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(takeMoney:) object:@800];
    [thread2 setName:@"second thread"];
    [thread1 start];
    [thread2 start];
}

ZPYAccount 中的 take 方法:

- (void)take:(double)count {
    double money = _balance;
    if (count <= money) {
        [NSThread sleepForTimeInterval:0.001];
        _balance = money - count;
        NSLog(@"thread:%@,取錢成功,余額為%f", [[NSThread currentThread] name], _balance);
    } else {
        NSLog(@"thread:%@,余額不足!", [[NSThread currentThread] name]);
    }
}

輸出結果顯示兩個線程都取錢成功、餘額都變成 700,明顯出錯。

1. @synchronized 實現同步

- (void)take:(double)count {
    @synchronized (self) {
        // 將需要同時執行的查錢、取錢放入同步代碼塊
        double money = _balance;
        if (count <= money) {
            [NSThread sleepForTimeInterval:0.001];
            _balance = money - count;
            NSLog(@"thread:%@,取錢成功,余額為%f", [[NSThread currentThread] name], _balance);
        } else {
            NSLog(@"thread:%@,余額不足!", [[NSThread currentThread] name]);
        }
    }
}

此時輸出變得合理:一個線程取錢成功後餘額為 700,另一個線程則提示餘額不足。

2. NSLock 同步鎖

_lock = [[NSLock alloc] init];

- (void)takelock:(double)count {
    [_lock lock];
    double money = _balance;
    if (count <= money) {
        [NSThread sleepForTimeInterval:0.001];
        _balance = money - count;
        NSLog(@"thread:%@,取錢成功,余額為%f", [[NSThread currentThread] name], _balance);
    } else {
        NSLog(@"thread:%@,余額不足!", [[NSThread currentThread] name]);
    }
    [_lock unlock];
}

使用 NSLock 同樣能保證線程安全,輸出結果與 @synchronized 一致。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved