IOS开发资料库iOS学习笔记程序员

轻松学iOS多线程之 NSThread 的基本使用

2016-09-27  本文已影响79人  BWLi420
NSThread

NSThread的几种创建方式
 NSThread *threadA = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"threadA"];
[threadA start];
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"threadB"];
    [self performSelectorInBackground:@selector(run:) withObject:@"threadC"];
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;
NSThread线程间的通信
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
 - (void)viewDidLoad {
    [super viewDidLoad];
}
 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //创建线程
    [NSThread detachNewThreadSelector:@selector(download) toTarget:self withObject:nil];
}
 - (void)download {    
    //获取开始时间
//    NSDate *start = [NSDate date];
    CFTimeInterval start = CFAbsoluteTimeGetCurrent();    
    //1.设置URL
    NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/bd315c6034a85edf9ba34e244b540923dd54758d.jpg"];
    //2.下载图片的二进制数据到本地
    NSData *imageData = [NSData dataWithContentsOfURL:url];
    //3.把二进制数据转换成图片
    UIImage *image = [UIImage imageWithData:imageData];
    //4.回到主线程设置展示图片
    // 4.1.方式一   waitUntilDone 是否等调用的方法执行完毕再继续执行后面的任务
//    [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];   
    //获取结束时间
//    NSDate *end = [NSDate date];
//    NSLog(@"用时:%f", [end timeIntervalSinceDate:start]);
    CFTimeInterval end = CFAbsoluteTimeGetCurrent();
    NSLog(@"用时:%f", end - start);   
   NSLog(@"--- END ---");
}
 - (void)showImage:(UIImage *)image {
    self.imageView.image = image;
    NSLog(@"%@", [NSThread currentThread]);
}
@end
上一篇下一篇

猜你喜欢

热点阅读