iOS 多線程編程之NSThread

1.NSThread的創建方式

a.動態方法創建

/**
 *  創建NSThread線程
 *
 *  @param target selector消息發送的對象
 *  @param sel    selector消息(即執行方法)
 *  @param arg    傳給selector的唯一參數,也可以是nil
 *
 *  @return NSThread線程對象
 */
- (nullable instancetype)initWithTarget:(id)target selector:(SEL)sel object:(nullable id)arg;
eg:
    //創建線程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil];
    //讓線程開始執行
    [thread start];

b.靜態方法創建

/**
 *  創建線程
 *
 *  @param selector selector消息(即執行方法)
 *  @param target   selector消息發送的對象
 *  @param argument 傳給selector的唯一參數,也可以是nil
 */
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
eg:
[NSThread detachNewThreadSelector:@selector(threadRun) toTarget:self withObject:nil];

注意:使用靜態方法創建NSThread時,創建的線程時默認開始的,如果使用動態方法一定要手動開始。

c.利用隱式創建線程的方法

[self performSelectorInBackground:@selector(reloadMyData) withObject:nil];

2.NSThread常用方法

a.獲取當前線程

NSThread *currentThread = [NSThread currentThread];

b.獲取主線程

NSThread *mainThread = [NSThread mainThread];

c.暫停當前線程

[NSThread sleepForTimeInterval:0.5];

3.NSThread中各個線程之間的通訊

a.在指定線程上進行操作

[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];

b.在主線程上進行操作

[self performSelectorOnMainThread:@selector(refreshData) withObject:nil waitUntilDone:YES];

c.在當前線程上進行操作

[self performSelector:@selector(run) withObject:nil];

4.NSThread優缺點

優點:

NSThread相比於GCD、NSOperation較輕量級,更能夠直接地控制線程對象

缺點:

需要自己管理線程的生命週期以及線程同步,會照成一定的系統開銷(線程同步對數據加鎖)

發佈了39 篇原創文章 · 獲贊 6 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章