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];
}
显示效果: