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
相關文章
相關標籤/搜索