您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 多執行緒開發入門:NSThread 用法詳解

編輯:iOS 相關教學

iOS 開發中實現多執行緒的方式主要有三種:NSThread、NSOperation 與 GCD。前面已經分別介紹過 NSOperation 和 GCD,為了讓學習路徑更完整,這次我們回到程式碼層面,把 NSThread 的常見用法整理一遍。

一、初始化並啟動一個執行緒

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // 取得當前執行緒
    NSThread *current = [NSThread currentThread];
    NSLog(@"當前執行緒為 %@", current);

    // 初始化執行緒
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    // 設定優先級,範圍 0.0 ~ 1.0
    thread.threadPriority = 1.0;
    thread.name = @"新執行緒1";
    [thread start];
}

- (void)run {
    NSLog(@"執行緒執行");
    NSThread *current = [NSThread currentThread];
    NSLog(@"當前執行緒為 %@", current);

    // 休眠兩秒,用來模擬耗時操作
    [NSThread sleepForTimeInterval:2];

    // 在子執行緒中也能取得主執行緒
    NSThread *mainThread = [NSThread mainThread];
    NSLog(@"子執行緒中取得主執行緒 %@", mainThread);
}

其中 currentThread 這個類方法非常實用,常用來確認某段程式碼究竟跑在哪一個執行緒上。

二、讓某個方法在背景執行

// 在背景開一條執行緒跑任務,被呼叫的方法內務必加上自動釋放池
[self performSelectorInBackground:@selector(run3) withObject:nil];

- (void)run3 {
    @autoreleasepool {
        NSLog(@"主執行緒3:%@,當前執行緒3:%@", [NSThread mainThread], [NSThread currentThread]);
    }
}

三、子執行緒做耗時運算,主執行緒更新 UI

這是多執行緒開發中最典型的場景。子執行緒中呼叫 performSelectorOnMainThread: 就能把結果拋回主執行緒更新界面。

// 測試在子執行緒中呼叫主執行緒更新 UI
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSThread *subThread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    // NSThread 可以精確控制執行緒何時開始
    [subThread start];
}

- (void)run {
    NSLog(@"主執行緒1:%@,當前執行緒1:%@", [NSThread mainThread], [NSThread currentThread]);
    // 以下方法需要在子執行緒中呼叫
    [self performSelectorOnMainThread:@selector(invocationMainThread)
                          withObject:nil
                       waitUntilDone:YES];
}

- (void)invocationMainThread {
    NSLog(@"主執行緒2:%@,當前執行緒2:%@", [NSThread mainThread], [NSThread currentThread]);
    NSLog(@"呼叫主執行緒更新 UI");
}

四、繼承 NSThread 自定義執行緒類

我們也可以建立一個繼承自 NSThread 的子類,並重寫其中的 main 方法——這個方法就是執行緒啟動後會自動執行的內容。

@implementation MyThread

- (void)main {
    NSLog(@"main 方法執行");
}

@end

接著照正常流程啟動即可,執行緒會自動去跑 main:

// 自定義子類,繼承自 NSThread 並重寫 main
/**
 * 執行的程式碼寫在 main 中,而不是透過 @selector 傳入。
 * 使用 main 的好處是:執行緒要跑的邏輯屬於物件本身,
 * 任何地方需要這個執行緒時直接取用即可,不必再重複實作一次。
 * 而直接建立 NSThread 的方式,執行緒內的方法都寫在當前的類文件中。
 */
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    MyThread *thread = [[MyThread alloc] init];
    [thread start];
}

五、執行緒休眠(延遲)

// 執行緒休眠兩秒,常用來模擬耗時任務
[NSThread sleepForTimeInterval:2];

以上五種用法構成了 NSThread 的日常工作集。至於三種多執行緒方案該如何取捨:NSThread 最貼近底層、可控性最高;GCD 最輕量;NSOperation 則在需要依賴關係、取消與最大併發數控制時更好用。三者都應該熟練掌握。

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