一 NSThread的基本使用
1)NSThread創(chuàng)建的四種方式
第一種 創(chuàng)建方式 alloc initwith......
特點:需要手動啟動線程,可以拿到線程對象進(jìn)行詳細(xì)設(shè)置
//創(chuàng)建線程
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"wendingding"];
//啟動線程
[thread start];
第1個參數(shù):目標(biāo)對象
第2個參數(shù):選擇器,線程啟動要調(diào)用哪個方法
第3個參數(shù):前面方法要接受的參數(shù)(最多只能接受一個參數(shù),沒有就寫nil)
第二種創(chuàng)建線程的方式:分離出一條子線程
特點:自動啟動線程,無法對線程進(jìn)行更詳細(xì)的設(shè)置
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"我是分離出來的子線程"];
第1個參數(shù):線程啟動調(diào)用的方法
第2個參數(shù):目標(biāo)對象
第3個參宿:傳遞給調(diào)用方法的參數(shù)
第三種創(chuàng)建線程的方式: 后臺創(chuàng)建
特點:自動啟動線程,無法進(jìn)行更詳細(xì)的設(shè)置
[self performSelectorInBackground:@selector(run:) withObject:@"我是后臺線程"];
第四種 自定義
需要自定義NSThread類重寫內(nèi)部方法實現(xiàn)
設(shè)置線程的屬性
設(shè)置線程名稱
thread.name = @"線程A"
設(shè)置線程的優(yōu)先級,優(yōu)先級的取值范圍是0.0~1.0 ,1.0表示最高 在不設(shè)置狀態(tài)下 默認(rèn)是0.5
thread.threadpriority = 1.0;
二 線程狀態(tài)
線程的各種狀態(tài): 新建 就緒 運(yùn)行 阻塞 死亡
常用的控制線程狀態(tài)的方法
[NSThread exit]//退出當(dāng)前線程
[NSThread sleepForTimeInterval:2.0]//阻塞線程
[NSThread sleepUntiDate:[NSDate dateWithTimeIntervalSinceNow:2.0]]//阻塞線程
注意線程死后不能復(fù)生
三 線程安全
01 前提:多個線程訪問同一塊資源會發(fā)生數(shù)據(jù)安全問題
02 解決方案 :加互斥鎖
03 代碼 : @synchronized(self){}
04 專業(yè)術(shù)語: 線程同步
05 原子核非原子屬性 (是否對set方法加鎖)
四 線程間通信
-(void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
// [self download2];
//開啟一條子線程來下載圖片
[NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
}
- (void)downioadImage
{
//1.確定要下載網(wǎng)絡(luò)圖片的url地址沈自,一個url唯一對應(yīng)著網(wǎng)絡(luò)上的一個資源
NSURL *url = [NSURL URLWithString:@"http://p6.qhimg.com/t01d2954e2799c461ab.jpg"];
//2.根據(jù)url地址下載圖片數(shù)據(jù)到本地(二進(jìn)制數(shù)據(jù)
NSData *data = [NSData dataWithContentsOfURL:url];
//3.把下載到本地的二進(jìn)制數(shù)據(jù)轉(zhuǎn)換成圖片
UIImage *image = [UIImage imageWithData:data];
//4.回到主線程刷新UI
//4.1 第一種方式
// [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
//4.2 第二種方式
// [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
//4.3 第三種方式
[self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
}
五 如何計算代碼段的執(zhí)行時間
//第一種方法
NSDate *start = [NSDate date];
//2.根據(jù)url地址下載圖片數(shù)據(jù)到本地(二進(jìn)制數(shù)據(jù))
NSData *data = [NSData dataWithContentsOfURL:url];
NSDate *end = [NSDate date];
NSLog(@"第二步操作花費的時間為%f",[end timeIntervalSinceDate:start]);
//第二種方法
CFTimeInterval start = CFAbsoluteTimeGetCurrent();
NSData *data = [NSData dataWithContentsOfURL:url];
CFTimeInterval end = CFAbsoluteTimeGetCurrent();
NSLog(@"第二步操作花費的時間為%f",end - start);