-
1.NSThread的基本使用
//第一種創(chuàng)建線程的方式:alloc init.
//特點:需要手動開啟線程佃声,可以拿到線程對象進(jìn)行詳細(xì)設(shè)置
//創(chuàng)建線程
/*
Target:目標(biāo)對象
selector:選擇器董饰,線程啟動要調(diào)用哪個方法
object:前面方法要接收的參數(shù)(最多只能接收一個參數(shù),沒有則傳nil)
*/
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"wendingding"];
//啟動線程
[thread start];
//第二種創(chuàng)建線程的方式:分離出一條子線程
//特點:自動啟動線程溅漾,無法對線程進(jìn)行更詳細(xì)的設(shè)置
/*
selector:線程啟動調(diào)用的方法
Target:目標(biāo)對象
withObject:傳遞給調(diào)用方法的參數(shù)
*/
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"我是分離出來的子線程"];
//第三種創(chuàng)建線程的方式:后臺線程
//特點:自動啟動線程,無法進(jìn)行更詳細(xì)設(shè)置
[self performSelectorInBackground:@selector(run:) withObject:@"我是后臺線程"];
-
2.主線程相關(guān)用法
-
+(NSThread *)mainThread; //獲得主線程
-
- (BOOL)isMainThread; //是否為主線程
-
+ (BOOL)isMainThread; //是否為主線程
-
-
3.設(shè)置線程的屬性
-
設(shè)置線程的名稱 thread.name = @"線程A";
-
設(shè)置線程的優(yōu)先級,注意線程優(yōu)先級的取值范圍為0.0~1.0之間,1.0表示線程的優(yōu)先級最高,如果不設(shè)置該值,那么理想狀態(tài)下默認(rèn)為0.5
-
thread.threadPriority = 1.0;
-
NSThread的聲明周期:當(dāng)線程執(zhí)行的任務(wù)完畢后會自動銷毀
-
4.線程的狀態(tài)
-
線程的各種狀態(tài):新建-就緒-運(yùn)行-阻塞-死亡
-
常用的控制線程狀態(tài)的方法
[NSThread exit];//退出當(dāng)前線程
[NSThread sleepForTimeInterval:2.0];//阻塞線程
[NSThread sleepUntilDate [NSDatedateWithTimeIntervalSinceNow:2.0]];//阻塞線程
注意:線程死了不能復(fù)生
-
5.線程安全
-
前提:多個線程訪問同一塊資源會發(fā)生數(shù)據(jù)安全問題
-
解決方案:加互斥鎖
-
相關(guān)代碼:@synchronized(self){}
-
專業(yè)術(shù)語-線程同步
-
原子和非原子屬性(是否對setter方法加鎖)nonatomic不為setter方法加鎖 业崖,atomic為setter方法加鎖,大多數(shù)情況下iOS開發(fā)不需要給setter方法加鎖
-
-
6.線程通信
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[NSThread detachNewThreadSelector:@selector(download) toTarget:self withObject:nil];
}
//開子線程下載圖片,回到主線程刷新UI
-(void)download
{
//1.確定URL
NSURL *url = [NSURL URLWithString:@"http://img4.duitang.com/uploads/blog/201310/18/20131018213446_smUw4.thumb.700_0.jpeg"];
//2.根據(jù)url下載圖片二進(jìn)制數(shù)據(jù)到本地
NSData *imageData = [NSData dataWithContentsOfURL:url];
//3.轉(zhuǎn)換圖片格式
UIImage *image = [UIImage imageWithData:imageData];
NSLog(@"download----%@",[NSThread currentThread]);
//4.回到主線程顯示UI
/*
MainThread:回到主線程要調(diào)用哪個方法
withObject:前面方法需要傳遞的參數(shù) 此處就是image
waitUntilDone:是否等待
YES:需要等showImage:方法執(zhí)行完畢后蓄愁,再打印---end---
NO:不需要等待showImage:方法執(zhí)行完畢双炕。
*/
[self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:NO];
// [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
NSLog(@"---end---");
}
//更新UI操作
-(void)showImage:(UIImage *)image
{
self.imageView.image = image;
NSLog(@"UI----%@",[NSThread currentThread]);
}