iOS中NSThread使用示例詳解
正文
NSThread的對象就代表一條線程,輕量級的線程操作,生命周期需要程序員控制,當任務執(zhí)行完畢之后被釋放掉。
創(chuàng)建和啟動線程
有三種創(chuàng)建方式 代碼:
- 1、
alloc init創(chuàng)建線程,需要手動啟動線程
- (void)createNewThread1{
//1.創(chuàng)建線程
// 第三個參數(shù)object: 前面調用方法需要傳遞的參數(shù) 可以為nil
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"rc"];
//設置線程的名字
thread.name = @"線程RC";
//設置優(yōu)先級 取值范圍 0.0 ~ 1.0 之間 最高是1.0 默認優(yōu)先級是0.5
thread.threadPriority = 1.0;
/*
iOS8.0之后新增 線程優(yōu)先級
@property NSQualityOfService qualityOfService;
NSQualityOfServiceUserInteractive --> Main thread
NSQualityOfServiceUserInitiated --> HIGH
NSQualityOfServiceUtility --> LOW
NSQualityOfServiceBackground --> Background
NSQualityOfServiceDefault --> Default
*/
// thread.qualityOfService = NSQualityOfServiceDefault;
//2.啟動線程
[thread start];
}
- 2、分離子線程,自動啟動線程
-(void)createNewThread2{
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分離子線程"];
}
- 3、開啟一條后臺線程,自動啟動
-(void)createNewThread3{
[self performSelectorInBackground:@selector(run:) withObject:@"開啟后臺線程"];
}
-(void)run:(NSString *)param{
NSLog(@"---run----%@---%@",[NSThread currentThread],param);
}
打?。?/p>
RCNSThreadDemo[4644:223899] ---run----<NSThread: 0x600000a98480>{number = 3, name = 線程RC}---rc
RCNSThreadDemo[4644:223901] ---run----<NSThread: 0x600000a98a00>{number = 4, name = (null)}---分離子線程
RCNSThreadDemo[4644:223902] ---run----<NSThread: 0x600000a99740>{number = 5, name = (null)}---開啟后臺線程
- 主線程相關用法
+ (NSThread *)mainThread; // 獲得主線程 - (BOOL)isMainThread; // 是否為主線程 + (BOOL)isMainThread; // 是否為主線程
- 獲得當前線程
NSThread *current = [NSThread currentThread];
線程的狀態(tài)
線程存在5種狀態(tài):新建 、就緒、運行、阻塞、死亡

- 啟動線程:進入就緒狀態(tài) -> 運行狀態(tài)。當線程任務執(zhí)行完畢,自動進入死亡狀態(tài)
- (void)start;
- 阻塞(暫停)線程:進入阻塞狀態(tài)
+ (void)sleepUntilDate:(NSDate *)date; + (void)sleepForTimeInterval:(NSTimeInterval)ti;
- 強制停止線程:進入死亡狀態(tài)
+ (void)exit;
注意:一旦線程停止(死亡)了,就不能再次開啟任務
線程安全
因為同一塊資源可能會被多個線程共享,也就是多個線程可能會訪問同一塊資源,比如:比如多個線程訪問同一個對象、同一個變量、同一個文件 當多個線程訪問同一塊資源時,很容易引發(fā)數(shù)據(jù)錯亂和數(shù)據(jù)安全問題
蘋果官方提供的安全隱患分析圖:

如上圖:有2個線程A、B同時read同一個地址獲得17,A進行加1得到18后寫入,此時B將拿到的17進行加1得到18后再寫入。 很明顯的,17做了兩次+1的操作,最后得到結果卻是18!??! 對于這種多個線程訪問同一對象獲得的結果是不可以預期的就出現(xiàn)了安全隱患。 對此蘋果官方也給出了解決辦法:

如上圖:當ThreadA 在訪問資源之前,先添加了一把鎖,執(zhí)行l(wèi)ock操作。再讀取資源, 執(zhí)行+ 1 操作,結束后寫入,同時將資源解鎖,執(zhí)行unlock操作。在這期間,其他的任何Thread是無法訪問這片資源的,必須等unlock操作結束后才可以訪。此時的其他Thread是出于等待狀態(tài)。
注意:加鎖是要消耗資源的。
關于鎖可以看看這篇iOS線程鎖及其性能
再引申一下:
原子和非原子屬性
OC在定義屬性時有nonatomic和atomic兩種選擇,想必我們大部分人用的都是nonatomic
- atomic:原子屬性,實際就是為setter方法加鎖(默認就是atomic),上面說過了,加鎖之后的線程是安全的,但是會消耗大量的資源。
- nonatomic:非原子屬性,不會為setter方法加鎖,非線程安全,適合內存小的移動設備
建議是:所有屬性都聲明為nonatomic;盡量避免多線程搶奪同一塊資源;盡量將加鎖、資源搶奪的業(yè)務邏輯交給服務器端處理,減小移動客戶端的壓力。
下面模擬線程安全隱患,創(chuàng)建3個線程,從開始0作+1操作,直到大于10 停止 代碼:
//使用nonatomic定義屬性
@property (nonatomic,assign) NSInteger totalCount;
- (void)createSafeThread{
self.threadA = [[NSThread alloc]initWithTarget:self selector:@selector(getTotal) object:nil];
self.threadB = [[NSThread alloc]initWithTarget:self selector:@selector(getTotal) object:nil];
self.threadC = [[NSThread alloc]initWithTarget:self selector:@selector(getTotal) object:nil];
[self.threadA start];
[self.threadB start];
[self.threadC start];
}
- (void)getTotal{
while (1) {
NSInteger count = self.totalCount;
if(count < 10) {
// 添加一個耗時操作,效果更明顯
for (NSInteger i = 0; i<88888; i++) {
NSInteger a = 1;
NSInteger b = 1;
a = a + b;
}
self.totalCount = count + 1;
NSLog(@"--*-**----%ld",self.totalCount);
}else{
break;
}
}
}
我們預期的打印應該是:從1~10依次打印出來,但是我們看真實的打印結果:
打?。?/p>
// 截取部分打印
RCNSThreadDemo[1763:182366] ------1
RCNSThreadDemo[1763:182365] ------2
RCNSThreadDemo[1763:182364] ------2
RCNSThreadDemo[1763:182365] ------3
RCNSThreadDemo[1763:182364] ------4
RCNSThreadDemo[1763:182366] ------3
RCNSThreadDemo[1763:182365] ------5
RCNSThreadDemo[1763:182364] ------5
RCNSThreadDemo[1763:182366] ------6
RCNSThreadDemo[1763:182364] ------7
一眼就能看出有問題,其實如果用GCD來模擬會更加明顯,在并發(fā)隊列中for循環(huán)添加異步任務看來復制,會造成壞內存訪問而程序崩潰。
上面也說了添加一個互斥鎖就會解決以上問題,這里使用的是:
@synchronized
使用格式:@synchronized(鎖對象) { // 需要鎖定的代碼 },其中的鎖對象必須是唯一的,一般傳self或當前一個全局的變量,如self.threadA。
注意:鎖定1份代碼只用1把鎖,用多把鎖是無效的
互斥鎖的優(yōu)缺點
- 優(yōu)點:能有效防止因多線程搶奪資源造成的數(shù)據(jù)安全問題
- 缺點:需要消耗大量的CPU資源
使用前提:多條線程搶奪同一塊資源 互斥鎖會造成 線程同步 ,即多條線程在同一條線上執(zhí)行(按順序地執(zhí)行任務)
上代碼:
- (void)getTotal{
while (1) {
@synchronized (self) {
NSInteger count = self.totalCount;
if(count < 10) {
// 添加一個耗時操作,效果更明顯
for (NSInteger i = 0; i<88888; i++) {
NSInteger a = 1;
NSInteger b = 1;
a = a + b;
}
self.totalCount = count + 1;
NSLog(@"------%ld",self.totalCount);
}else{
break;
}
}
}
}
線程間通信
線程間通信常用方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait; - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
以下載圖片為例: 代碼:
- (void)downloadImage{
[NSThread detachNewThreadSelector:@selector(download) toTarget:self withObject:nil];
}
- (void)download{
NSURL *url = [NSURL URLWithString:@"http://00.minipic.eastday.com/20170227/20170227134901_e45455144ba23b7cee75f292229151b1_21.jpeg"];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
//主線程顯示圖片 waitUntilDone :是否等待,指的是后面代碼的執(zhí)行是否需要等待本次操作結束
// 第一種
// [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
// 第二種
[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
}
//更新UI操作
-(void)showImage:(UIImage *)image{
self.imageView.image = image;
NSLog(@"UI----%@",[NSThread currentThread]);
}
很簡單,開啟一個子線程來下載圖片,再去主線程更新UI。
以上就是iOS中NSThread使用示例詳解的詳細內容,更多關于iOS中NSThread使用的資料請關注腳本之家其它相關文章!
相關文章
iOS微信瀏覽器回退不刷新實例(監(jiān)聽瀏覽器回退事件)
下面小編就為大家?guī)硪黄猧OS微信瀏覽器回退不刷新實例(監(jiān)聽瀏覽器回退事件)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05

