前言:關(guān)于線程和進(jìn)程荆烈,其實(shí)不難理解淌山,進(jìn)程就相當(dāng)于手機(jī)中的視頻播放器裸燎,線程就相當(dāng)于在視頻播放器中觀看視頻,多線程相當(dāng)于觀看視頻的同時泼疑,也下載視頻德绿。
/*
加載一張圖片
1、創(chuàng)建一個UIImageView退渗,并放在父視圖上
2移稳、創(chuàng)建一個子線程
3、通過url獲取網(wǎng)絡(luò)圖片
4会油、回到主線程
5个粱、在主線程更新UI
*/
開辟線程的兩種方式:
1、手動開啟線程:
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread1:) object:@"thread1"];
[thread start];
2翻翩、自動開啟方式:
[NSThread detachNewThreadSelector:@selector(thread1:) toTarget:self withObject:@"thread1"];
獲取當(dāng)前線程:
[NSThread currentThread];
線程的優(yōu)先級:(0-1)默認(rèn)是0.5
[NSThread setThreadPriority:1.0];
下面以加載一張網(wǎng)絡(luò)圖片為例具體介紹:
#import "ViewController.h"
#define kUrl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943"
@interface ViewController ()
{
UIImageView *imageView;
UIImage *image;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor brownColor];
// 消除導(dǎo)航欄的影響
self.edgesForExtendedLayout = UIRectEdgeNone;
#pragma mark - ---NSThread開辟線程的兩種方式*****
/*
* 創(chuàng)建手動開啟方式
* 第三個參數(shù):就是方法選擇器選擇方法的參數(shù)
*/
// NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread1:) object:@"thread1"];
// 開啟線程
//[thread start];
/*
*創(chuàng)建并自動開啟方式
*/
[NSThread detachNewThreadSelector:@selector(thread1:) toTarget:self withObject:@"thread1"];
NSLog(@"viewDidload方法所在的線程 %@",[NSThread currentThread]);
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
[self.view addSubview:imageView];
}
// 在子線程執(zhí)行的方法
-(void)thread1:(NSString *)sender{
// [NSThread currentThread] 獲取到當(dāng)前所在的信息
//NSThread *thread = [NSThread currentThread];
// thread.name = @"我是子線程";
// NSLog(@"thread1方法所在的線程%@",thread);
// [NSThread isMainThread]判斷當(dāng)前線程是否是主線程
// BOOL ismainThread = [NSThread isMainThread];
// BOOL isMultiThread = [NSThread isMultiThreaded];
// setThreadPriority 設(shè)置線程的優(yōu)先級(0-1)
//[NSThread setThreadPriority:1.0];
// sleepForTimeInterval 讓線程休眠
//[NSThread sleepForTimeInterval:2];
#pragma ----
// 從網(wǎng)絡(luò)加載圖片拼接并將它轉(zhuǎn)換為data類型的數(shù)據(jù)
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kUrl]];
image = [UIImage imageWithData:data];
// waitUntilDone設(shè)為YES都许,意味著UI更新完才會去做其他操作
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
}
-(void)updateUI:(UIImage *)kimage{
imageView.image = kimage;
NSLog(@"updateUI方法所在的線程%@",[NSThread currentThread]);
}