NSThread
- 特點(diǎn):
- 更加面向?qū)ο?/li>
- 簡(jiǎn)單易用,可直接操作線程對(duì)象
- 使用語言:OC語言
- 使用頻率:偶爾使用
- 線程生命周期:由程序員進(jìn)行管理,任務(wù)結(jié)束后自行銷毀
NSThread的幾種創(chuàng)建方式
- 方式一:
- 優(yōu)點(diǎn):能拿到線程對(duì)象
- 缺點(diǎn):需要手動(dòng)啟動(dòng)線程
NSThread *threadA = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"threadA"];
[threadA start];
- 方式二:
- 優(yōu)點(diǎn):自動(dòng)啟動(dòng)線程
- 缺點(diǎn):不能拿到線程對(duì)象
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"threadB"];
- 方式三:(后臺(tái)線程)
- 優(yōu)點(diǎn):自動(dòng)啟動(dòng)線程
- 缺點(diǎn):不能拿到線程對(duì)象
[self performSelectorInBackground:@selector(run:) withObject:@"threadC"];
- 方式四:(自定義線程)
- 缺點(diǎn):需要自定義 NSThread 類妓蛮,重寫自定義類的 main 方法
- 需要手動(dòng)開啟子線程
BWThread *threadD = [[BWThread alloc] init];
[threadD start];
-(void)main {
NSLog(@"%@", [NSThread currentThread]);
NSLog(@"自定義線程需要重寫 main 方法");
}
NSThread常用屬性
threadA.name = @"threadA";
[threadB setName:@"threadB"];
threadC.name = @"threadC";
threadA.threadPriority = 1.0;
threadC.threadPriority = 0.1;
- 優(yōu)先級(jí)的取值范圍是 0~1.0,默認(rèn)情況下是 0.5
- 系統(tǒng)在執(zhí)行任務(wù)時(shí),會(huì)根據(jù)優(yōu)先級(jí)的大小調(diào)整任務(wù)的執(zhí)行順序蒲肋,優(yōu)先級(jí)大的任務(wù)會(huì)先執(zhí)行。
NSThread線程間的通信
- 涉及到 UI 界面的操作都要放到主線程中執(zhí)行
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//創(chuàng)建線程
[NSThread detachNewThreadSelector:@selector(download) toTarget:self withObject:nil];
}
- (void)download {
//獲取開始時(shí)間
// NSDate *start = [NSDate date];
CFTimeInterval start = CFAbsoluteTimeGetCurrent();
//1.設(shè)置URL
NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/bd315c6034a85edf9ba34e244b540923dd54758d.jpg"];
//2.下載圖片的二進(jìn)制數(shù)據(jù)到本地
NSData *imageData = [NSData dataWithContentsOfURL:url];
//3.把二進(jìn)制數(shù)據(jù)轉(zhuǎn)換成圖片
UIImage *image = [UIImage imageWithData:imageData];
//4.回到主線程設(shè)置展示圖片
// 4.1.方式一 waitUntilDone 是否等調(diào)用的方法執(zhí)行完畢再繼續(xù)執(zhí)行后面的任務(wù)
// [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
// 4.2.方式二
// [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
// 4.3.方式三
[self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
//獲取結(jié)束時(shí)間
// NSDate *end = [NSDate date];
// NSLog(@"用時(shí):%f", [end timeIntervalSinceDate:start]);
CFTimeInterval end = CFAbsoluteTimeGetCurrent();
NSLog(@"用時(shí):%f", end - start);
NSLog(@"--- END ---");
}
- (void)showImage:(UIImage *)image {
self.imageView.image = image;
NSLog(@"%@", [NSThread currentThread]);
}
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者