iOS多线程-线程间通信

复习下线程的基础知识, 这里主要是参考文顶顶多线程篇复习写的。

一、简单说明

线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信

线程间通信的体现

  • 1个线程传递数据给另1个线程
  • 在1个线程中执行完特定任务后,转到另1个线程继续执行任务

线程间通信常用方法

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait;
线程间通信示例 – 图片下载

代码示例


@interface ViewController ()

@property (strong, nonatomic) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 20, 300, 300)];
    _imageView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_imageView];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //在子线程下载
    [self performSelectorInBackground:@selector(download) withObject:nil];
}

/**
 *  下载图片
 */
- (void)download {
    NSLog(@"download---%@", [NSThread currentThread]);
    // 1.图片地址,其实是一行
    NSString *urlStr = @"https://timgsa.baidu.com/timg?image&quality=80"
    @"&size=b9999_10000&sec=1559061649110&di=adfd3a30f3bb4868722529859d14ae9d"
  @"&imgtype=0&src=http%3A%2F%2Fpic31.nipic.com%2F20130719%2F9885883_095141604000_2.jpg";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 2.根据地址下载图片的二进制数据(这句代码最耗时)
    NSLog(@"---begin");
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSLog(@"---end");
    
    // 3.设置图片
    UIImage *image = [UIImage imageWithData:data];
    
    // 4.回到主线程,刷新UI界面(为了线程安全)
    [self performSelectorOnMainThread:@selector(downloadFinished:) withObject:image waitUntilDone:NO];
//    [self performSelector:@selector(downloadFinished:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
//    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    
    NSLog(@"-----done----");
}

- (void)downloadFinished:(UIImage *)image {
    self.imageView.image = image;
    NSLog(@"downloadFinished---%@", [NSThread currentThread]);
}

@end

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 进程 什么是进程 进程是指在系统中正在运行的一个应用程序 每个进程之间是独立的,每个进程均运行在其专用且受保护的内...
    45b645c5912e阅读 3,265评论 0 5
  • 【JAVA 线程】 线程 进程:是一个正在执行中的程序。每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者...
    Rtia阅读 7,692评论 2 20
  • 前言 iOS多线程有四种:pthread(最古老的),NSThread,NSOperation,GCD 一、进程和...
    GitHubPorter阅读 2,784评论 0 3
  • iOS多线程编程 基本知识 1. 进程(process) 进程是指在系统中正在运行的一个应用程序,就是一段程序的执...
    陵无山阅读 11,298评论 1 14
  • 简单方法安装php的zip扩展pecl-zip 环境:unbuntu16.04, php7.0, apache2....
    aliasToHell阅读 7,779评论 1 0