IOS开发—多线程简介

IOS多线程


一、进程与线程的区别

进程:指每个正在运行的程序,如QQ、酷狗音乐等。

线程:每个进程至少有一个线程,每一个线程代表该进程中的一项任务。所谓多线程,就是该进程中有好多个任务在同时执行,注意是同时执行(实际是CPU快速调度各线程,造成了同时执行的假象)。

 

二、IOS多线程

1、一个NSThread就代表一条线程。

2、获取线程的方法:

+(NSThread)mainThread; 获取主线程

+(NSThread)currentThread; 获取当前线程

3、其他用法:

-(BOOL)isMainThread;//是否主线程

+(BOOL)isMainThread;//是否主线程

4、创建和启动线程的方法:

(1).创建线程后手动启动线程:

//创建线程,启动后执行run方法

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];

//开启线程

[thread start];

(2).创建线程后自动启动线程:

[NSThread detachNewThreadSelector:@selector(run) toTarger:self wthObject:nil];

(3).隐式创建线程并自动启动:

[self performSelectorInBackground:@selector(run) withObject:nil];

       

三、线程之间的通信

1、简单说明:

在1个进程中,线程之间往往不是独立的,彼此之间通常存在通信联系,体现在:(1)一个线程传递数据给另一个线程; (2)在一个线程中完成任务后转到另一个线程继续执行任务。

2、线程间通信常用方法:

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

-(void)performSelector:(SEL)selector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait;

3、代码示例:(设置图片)

#import "ViewController.h"
@interface ViewController ()
 @property (nonatomic, strong) IBOutlet UIImageView *imageView;
 @end
 
@implementationViewController
 - (void)viewDidLoad {
    [super viewDidLoad];
    _imageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _imageView.backgroundColor = [UIColor whiteColor];
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:_imageView];
}
 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self performSelectorInBackground:@selector(loadImage) withObject:nil];
}
 
- (void)loadImage
{
    NSString *urlString = @"https://www.baidu.com/img/bdlogo.png";
    NSURL *URL = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:URL];
    UIImage *image = [UIImage imageWithData:data];

	//放到主线程中设置图片方法一
	[self performSelector:@selector(setMainImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
	//方法二
	//   [self.imageView performSelectorOnMainThread:@selector(setImage:)withObject:image waitUntilDone:nil];
}
 
- (void)setMainImage:(UIImage *)image
{
    [_imageView setImage:image];
}


显示效果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值