iOS多线程编程

来源:互联网 发布:手机淘宝安全中心官网 编辑:程序博客网 时间:2024/06/16 16:26

一、什么是多线程

a)               进程是运行着的程序;

b)              一个进程至少包含一个线程(主线程,界面更新UIKit);

c)               线程共用程序内存,但每个线程都有自己的stack空间;

d)              多线程就是多个执行流,可以同步或异步,是一种并发执行技术。

二、iOS中实现方法

a)               pthread:iOS是某个版本的Mac OS所以可以使用unix中的线程方法;

b)              NSThread:轻量级多线程技术,需要自己管理线程的生命周期;

c)               NSOperation &NSOperationQueen:相比NSThread技术,使用更加简单,不需要线程管理,直接使用;

d)              GCD(Grand Central Dispatch):Ios4.0版本推出,用于取代NSThread和NSOperation,简单方便,功能强大,推荐使用。

三、NSThread

注:可继承NSThread重写main方法

a)               + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullableid)argument;

b)              - (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullableid)argument NS_AVAILABLE(10_5,2_0);

c)               - (void)performSelectorInBackground:(SEL)aSelector withObject:(nullableid)arg NS_AVAILABLE(10_5,2_0);//属于NSObject

d)              /*更新主线程UI*/- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullableid)arg waitUntilDone:(BOOL)wait;//属于NSObject

e)               加锁:NSLock/NSCondition

四、NSOperation& NSOperationQueen

a)               NSInvocationOperation/NSBlockOperation/NSOperation/NSOperationQueen

b)              可继承NSOperation实现main方法

c)               只要把NSOperation的对象放到NSOperationQueen中即会进行多线程的运行

d)              并发执行/非并发执行

e)               -(void)start

f)                 – (BOOL)isConcurrent

g)               – (BOOL)isFinishd

h)              – (BOOL)isExecuting

i)                  – (void)main

五、GCD(GrandCentral Dispatch)

a)               GCD是iOS在4.0版本后推出的,用于取代以上方式的多线程,其可根据程序的任务队列合理分配核去处理,充分利用硬件多核,效率高。

b)              概念:任务和队列(串行队列/并行队列/同步任务/异步任务)

c)               api:dispatch_queue_t/dispatch_queue_create/dispatch_get_main_queue/dispatch_get_global_queue/dispatch_sync/dispatch_async/dispatch_group_t/dispatch_group_create/dispatch_group_async/dispatch_group_notify

示例代码:


////  ViewController.m//  ThreadDemo////  Created by LiLeo on 16/6/24.//  Copyright © 2016年 LeoLi. All rights reserved.//#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UIImageView *imageView;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    NSString * string = @"http://c.hiphotos.baidu.com/image/pic/item/ae51f3deb48f8c54469d4dc23e292df5e1fe7f95.jpg";    /*NSThread的三种方法*///    [NSThread detachNewThreadSelector:@selector(downloadImageByUrl:) toTarget:self withObject:string];//    NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImageByUrl:) object:string];//    [thread start];    //[self performSelectorInBackground:@selector(downloadImageByUrl:) withObject:string];        /*NSOperation的实现方法*/    /*     * 若要继承NSOperation有两种方式,只实现main方法的是非同步的,同步的需要实现:start/isConcurrent/isFinished     *///    NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImageByUrl:) object:string];//    NSOperationQueue * queue = [[NSOperationQueue alloc] init];//    [queue addOperation:operation];    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    dispatch_async(queue, ^{        NSURL * url = [NSURL URLWithString:string];        NSData * data = [NSData dataWithContentsOfURL:url];        UIImage * image = [[UIImage alloc] initWithData:data];        dispatch_async(dispatch_get_main_queue(), ^{            _imageView.image = image;        });    });}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (void)downloadImageByUrl:(NSString *)string {    NSURL * url = [NSURL URLWithString:string];    NSData * data = [[NSData alloc] initWithContentsOfURL:url];    UIImage * image = [UIImage imageWithData:data];    [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];}- (void)updateImage:(UIImage *)image {    _imageView.image = image;}@end


六、参考文档

a)               http://mobile.51cto.com/iphone-403490.htm

b)              http://blog.csdn.net/totogo2010/article/details/8010231

c)               http://www.cnblogs.com/wendingding/p/3805088.html

d)              http://www.cocoachina.com/ios/20150731/12819.html           

 

0 0
原创粉丝点击