IOS的三种多线程技术

ONE ------------------------------------------

#import "ViewController.h"
#define ROW 5
#define COLUMN 3
#define IMAGE_COUNT ROW*COLUMN
#define WIDTH 100//图片宽
#define HEIGHT WIDTH//图片高

@interface ViewController ()
{
    NSMutableArray *_imageViews;
    NSArray *arrayImage;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    arrayImage = @[
                                @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                                @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                                @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                                @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                                @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                                @"http://hiphotos.baidu.com/90008com/pic/item/fdaef1ea2eea7ff3d539c904.jpeg",
                                @"http://p7.qhimg.com/t01308022902bb3cc15.jpg",
                                @"http://www.33lc.com/article/UploadPic/2012-8/2012815167420064.jpg",
                                @"http://d.3987.com/jmfghjgqbz.120925/004.jpg",
                                @"http://img.bbs.duba.net/month_1011/1011020907c8b129640ca5a7e7.jpg",
                                @"http://www.deskcar.com/desktop/car/201337162241/6.jpg",
                                @"http://pic11.nipic.com/20101117/778850_171649021175_2.jpg",
                                @"http://kuoo8.com/wall_up/hsf2288/200911/200911031144096643.jpg",
                                @"http://pic.4j4j.cn/upload/pic/20130305/6399c64adb.jpg",
                                @"http://www.deskcar.com/desktop/car/2005/2007121201442/10.jpg"
                                
                                ];

    [self layout];
}

- (void)layout
{
    _imageViews = [NSMutableArray array];
    for (int r = 0; r < COLUMN; r++) {
        for (int c = 0; c < ROW; c++) {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(18.75 + r * 118.75, 20 + c * 118.75, WIDTH, HEIGHT)];
            imageView.backgroundColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:0.8];
            [self.view addSubview:imageView];
            [_imageViews addObject:imageView];
        }
    }
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(50, 620,275,30)];
    [button setTitle:@"加载图片" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(useMultiThread) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}
- (void)updateImage : (NSArray *)arr
{
    UIImage *image = [UIImage imageWithData:arr[0]];
    UIImageView *imageView = _imageViews[[arr[1] intValue]];
    imageView.image = image;
}

- (void)loadImage : (NSNumber *)index{
//    //优先下载
    if (![index isEqual:@14]) {
        //若是当前进程不是最后一个,就休眠2秒
        [NSThread sleepForTimeInterval:3];
    }
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:arrayImage[[index intValue]]]];
    NSArray *arrData = @[data,index];
    [self performSelectorOnMainThread:@selector(updateImage:) withObject:arrData waitUntilDone:YES];
}
- (void)useMultiThread
{
    for (int i = 0; i < IMAGE_COUNT; i++) {
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
        thread.name = [NSString stringWithFormat:@"个人线程:%d",i];
        [thread start];//启动
    }
}

#pragma mark 改变线程优先级
//提升优先级是提升他被加载的概率,可是未必就第一个加载。1.其余进程是先启动的2.网络情况咱们没办法修改
//-(void)useMultiThrea{
//    NSMutableArray *array = [NSMutableArray array];
//    for (int i = 0; i < IMAGE_COUNT; i++) {
//        NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
//        //设置进程优先级(范围0-1)
//    if (i == IMAGE_COUNT-1) {
//        thread1.threadPriority = 1.0;
//    }else{
//        thread1.threadPriority = 0;
//    }
//        [array addObject:thread1];
//    }
//    for (int i = 0; i<IMAGE_COUNT; i++) {
//        NSThread *thread2 = array[i];
//        [thread2 start];
//    }
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

TWO-----------------------------------------------------------------

#import "ViewController.h"
#define ROW 5
#define COLUMN 3
#define IMAGE_COUNT ROW*COLUMN
#define WIDTH 100//图片宽
#define HEIGHT WIDTH//图片高

@interface ViewController ()
{
    NSMutableArray *_imageViews;
    NSArray *arrayImage;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    arrayImage = @[
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://hiphotos.baidu.com/90008com/pic/item/fdaef1ea2eea7ff3d539c904.jpeg",
                   @"http://p7.qhimg.com/t01308022902bb3cc15.jpg",
                   @"http://www.33lc.com/article/UploadPic/2012-8/2012815167420064.jpg",
                   @"http://d.3987.com/jmfghjgqbz.120925/004.jpg",
                   @"http://img.bbs.duba.net/month_1011/1011020907c8b129640ca5a7e7.jpg",
                   @"http://www.deskcar.com/desktop/car/201337162241/6.jpg",
                   @"http://pic11.nipic.com/20101117/778850_171649021175_2.jpg",
                   @"http://kuoo8.com/wall_up/hsf2288/200911/200911031144096643.jpg",
                   @"http://pic.4j4j.cn/upload/pic/20130305/6399c64adb.jpg",
                   @"http://www.deskcar.com/desktop/car/2005/2007121201442/10.jpg"
                   
                   ];
    
    [self layout];
}

- (void)layout
{
    _imageViews = [NSMutableArray array];
    for (int r = 0; r < COLUMN; r++) {
        for (int c = 0; c < ROW; c++) {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(18.75 + r * 118.75, 20 + c * 118.75, WIDTH, HEIGHT)];
            imageView.backgroundColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:0.8];
            [self.view addSubview:imageView];
            [_imageViews addObject:imageView];
        }
    }
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(50, 620,275,30)];
    [button setTitle:@"加载图片" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(useMultiThread) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}
- (void)updateImage : (NSArray *)arr
{
    UIImage *image = [UIImage imageWithData:arr[0]];
    UIImageView *imageView = _imageViews[[arr[1] intValue]];
    imageView.image = image;
}
- (void)loadImage : (NSNumber *)index{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:arrayImage[[index intValue]]]];
    NSArray *arrData = @[data,index];
    //更新UI界面,调用主线程队列
    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
        [self updateImage:arrData];
    }];
}
-(void)useMultiThread{
    //1.建立一个操做队列
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
    operationQueue.maxConcurrentOperationCount = 5;//设置最大并发线程数
    //2.向队列添加操做
//    for (int i = 0; i < IMAGE_COUNT; i++) {
        //方法1:建立操做块,添加到队列
//        NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
//            [self loadImage:[NSNumber numberWithInt:i]];
//        }];
//        //向操做队列 添加 操做
//        [operationQueue addOperation:blockOperation];
        //方法2 祷文Invocation
//        NSInvocationOperation *invocationOpe = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
//        [operationQueue addOperation:invocationOpe];
        //方法3:控制线程的执行顺序
        NSBlockOperation *lastOpe = [NSBlockOperation blockOperationWithBlock:^{
            [self loadImage:@(IMAGE_COUNT-1)];
        }];
        for (int j = 0; j < IMAGE_COUNT-1; j++) {
            NSBlockOperation *normalOpe = [NSBlockOperation blockOperationWithBlock:^{
                [self loadImage:[NSNumber numberWithInt:j]];
            }];
            //设置依赖操做(普通依赖最后的)
            [normalOpe addDependency:lastOpe];
            [operationQueue addOperation:normalOpe];
        }
            [operationQueue addOperation:lastOpe];
    
//    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


THREE---------------------------------------------------------------------


#import "ViewController.h"

@interface ViewController ()
{
    UIImageView *_imageView;
    NSMutableArray *_imageArray;
    NSArray *arrayImage;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    arrayImage = @[
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://pic19.nipic.com/20120310/8061225_093309101000_2.jpg",
                   @"http://hiphotos.baidu.com/90008com/pic/item/fdaef1ea2eea7ff3d539c904.jpeg",
                   @"http://p7.qhimg.com/t01308022902bb3cc15.jpg",
                   @"http://www.33lc.com/article/UploadPic/2012-8/2012815167420064.jpg",
                   @"http://d.3987.com/jmfghjgqbz.120925/004.jpg",
                   @"http://img.bbs.duba.net/month_1011/1011020907c8b129640ca5a7e7.jpg",
                   @"http://www.deskcar.com/desktop/car/201337162241/6.jpg",
                   @"http://pic11.nipic.com/20101117/778850_171649021175_2.jpg",
                   @"http://kuoo8.com/wall_up/hsf2288/200911/200911031144096643.jpg",
                   @"http://pic.4j4j.cn/upload/pic/20130305/6399c64adb.jpg",
                   @"http://www.deskcar.com/desktop/car/2005/2007121201442/10.jpg"
                   
                   ];

    [self layout];
    [self GCDdemoRun];
}
-(void)layout{
    _imageArray = [NSMutableArray array];
    for (int i = 0 ; i<5; i++) {
        for (int j = 0; j<3; j++) {
            _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(18.75 + j * 118.75, 20 + i * 118.75, 100, 100)];
            _imageView.backgroundColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:0.8];
            [self.view addSubview:_imageView];
            [_imageArray addObject:_imageView];
        }
    }
}
//-(void)GCDdemoRun{
//    //队列组
//    dispatch_group_t groupQueue = dispatch_group_create();
//    //组1开始异步执行任务
//    dispatch_group_async(groupQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSLog(@"组1任务完成");
//    });
//    //组2开始异步执行任务
//    dispatch_group_async(groupQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSLog(@"组2任务完成");
//    });
//    //监听组队列任务完成
//    dispatch_group_notify(groupQueue, dispatch_get_main_queue(), ^{
//        NSLog(@"组队列任务所有结束");
//    });
//}
//锁机制
//IOS中提供经常使用的两种方法
//1.NSLock
//2.@synchronized
//-(void)GCDdemoRun{
//    //全局队列(可开启多个线程)
//    //参数1:线程优先级(high,default,low)
//    //参数2:标记参数,目前没有用,通常写0;
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    //建立线程执行任务
//    for (int i = 0; i < 15; i++) {
//        //异步执行队列任务
//        dispatch_async(globalQueue, ^{
//            [self loadImage:i];
//        });
//    }
//}
-(void)GCDdemoRun{
    //串行队列
    //参数1:队列名称  参数2:队列类型
    dispatch_queue_t serialQueue = dispatch_queue_create("mySerialQueue", DISPATCH_QUEUE_SERIAL);
    //建立1个线程(执行15个任务)
    for (int i = 0; i < 15; i++) {
        //异步执行队列任务
        //因为是串行队列,因此不会建立新的线程
        dispatch_async(serialQueue, ^{
            [self loadImage:i];
            sleep(1);//休眠1秒
        });
    }
    
}
-(void)loadImage:(int)index{
    //打印当前操做线程
    NSLog(@"%@",[NSThread currentThread]);
    //获取图片数据
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:arrayImage[index]]];
    //获取主队列,更新UI
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    //同步执行
    //当前线程正在执行任务时,不会开启新线程
    dispatch_sync(mainQueue, ^{
        UIImage *image = [UIImage imageWithData:data];
        UIImageView *imageView = _imageArray[index];
        imageView.image = image;
    });
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
相关文章
相关标签/搜索