多線程的三種方式
※NSThread:共有三種創(chuàng)建方式屏鳍,任選其一
方式1.實例方法來創(chuàng)建一個子線程,需要手動來開啟,若不手動開啟卧秘,就不會運行
- (void)test1{
//判斷當前的線程是不是主線程,非零為真
BOOL isMainThread = [NSThread isMainThread];
NSLog(@"isMainThread = %d",isMainThread);
//實例方法來創(chuàng)建一個子線程官扣,需要手動來開啟翅敌,若不手動開啟,就不會運行
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(doSth) object:nil];
//給線程起名字惕蹄,沒啥用
thread.name = @"子線程";
//啟動線程
[thread start];
}
方式2.類方法開啟一條新的子線程蚯涮,不需要手動開啟,會直接執(zhí)行doSth方法
- (void)test2{
//類方法開啟一條新的子線程卖陵,不需要手動開啟遭顶,會直接執(zhí)行doSth方法
[NSThread detachNewThreadSelector:@selector(doSth) toTarget:self withObject:nil];
}
方式3.
- (void)test3{
//隱式地創(chuàng)建一條新的子線程
[self performSelectorInBackground:@selector(doSth) withObject:nil];
}
線程中的方法
- (void)doSth{
//判斷是不是子線程
BOOL isMainThread = [NSThread isMainThread];
NSLog(@"isMainThread = %d",isMainThread);
// 打印當前的線程
NSLog(@"%@",[NSThread currentThread]);
NSURL *url = [NSURL URLWithString:@"https://ss0.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/image/h%3D200/sign=875aa8d07fec54e75eec1d1e89399bfd/241f95cad1c8a7866f726fe06309c93d71cf5087.jpg"];
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSLog(@"%@",data);
//self.imageView.image = [UIImage imageWithData:data]; //在這里(子線程中)直接賦值是不對的,應該用線程間的通訊泪蔫,再次提醒不允許在子線程中刷UI0羝臁!A萌佟`露摺!婿滓!
//線程間通訊(傳值)
[self performSelectorOnMainThread:@selector(updateUI:) withObject:data waitUntilDone:YES];
}
//回到主線程中刷新UI
- (void)updateUI:(NSData*)data{
self.imageView.image = [UIImage imageWithData:data];
}
線程加鎖:當有多個線程同時訪問或修改同一個資源時,會出問題粥喜,所以需要進行加鎖操作凸主,此處介紹兩種加鎖操作。
注:
1额湘、當有多個線程同時訪問或修改同一個資源時卿吐,會出現(xiàn)問題,此時需要使用線程鎖來解決
2锋华、當添加線程鎖時嗡官,是對資源的管理,而不是對線程的管理
3毯焕、對資源添加線程鎖衍腥,其實就是把這個資源變成原子性操作(atomic)
@interface ViewController ()
{
//蘋果總數(shù)
NSInteger _totalApple;
NSLock *_lock;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
_totalApple = 20;
//創(chuàng)建鎖
_lock = [[NSLock alloc]init];
//創(chuàng)建兩個子線程(隱式方法)
[self performSelectorInBackground:@selector(getApple1) withObject:nil];
[self performSelectorInBackground:@selector(getApple2) withObject:nil];
//當有多個線程同時訪問或修改同一個資源時,會出問題纳猫,所以需要進行加鎖操作婆咸,此處介紹兩種加鎖操作。
}
- (void)getApple1{
#if 0
//加鎖
[_lock lock];
for (int i=10; i>0; i--) {
_totalApple--;
NSLog(@"A--%ld",_totalApple);
}
//解鎖
[_lock unlock];
#else
@synchronized(self) {
for (int i=10; i>0; i--) {
_totalApple--;
NSLog(@"A--%ld",_totalApple);
}
}
#endif
}
- (void)getApple2{
#if 0
//加鎖
[_lock lock];
for (int i=10; i>0; i--) {
_totalApple--;
NSLog(@"B--%ld",_totalApple);
}
//解鎖
[_lock unlock];
#else
@synchronized(self) {
for (int i=10; i>0; i--) {
_totalApple--;
NSLog(@"B--%ld",_totalApple);
}
}
#endif
}