NSThread-多線程

前言:關(guān)于線程和進程,其實不難理解,進程就相當(dāng)于手機中的視頻播放器,線程就相當(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)默認是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]);


}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容