GCD_Grand central dispatch 解決資源搶奪問題(買車票) shareSDK


//GCD_Grand central dispatchc++

//
//  ViewController.m
//  GCD_Grand central dispatch
//
//  Created by DC020 on 15/12/25.
//  Copyright (c) 2015年 Bill. All rights reserved.
//

#import "ViewController.h"
#define ROW 3
#define CONLUMN 5
#define imageCount WINTH * CONLUNM

@interface ViewController (){
    NSMutableArray *_MutableArray;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _MutableArray = [NSMutableArray array];
    for (int c = 0; c < CONLUMN; c++) {
        for (int r = 0; r < ROW; r++) {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(18.75+r*118.75, 70+c*118.75, 100, 100)];
            imageView.backgroundColor = [UIColor redColor];
            [self.view addSubview:imageView];
            [_MutableArray addObject:imageView];
        }
    }
    UIButton *button  = [[UIButton alloc]initWithFrame:CGRectMake(50, 40, 275, 20)];

    [button addTarget:self action:@selector(GCDdemoRun) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"加載圖片" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.view addSubview:button];

}
-(void)loadImage:(int)Index{
        //打印當前線程
    NSLog(@"%@",[NSThread currentThread]);
    //獲取圖片數據
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:@"http://b.zol-img.com.cn/desk/bizhi/image/7/2560x1600/1447404575613.jpg"]]];
    //獲取主隊列,更新UI
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    //同步執行
    //當前線程正在執行任務時,不會開啓新線程
    dispatch_sync(mainQueue, ^{
        UIImage *image = [UIImage imageWithData:data];
        UIImageView *imageView = _MutableArray[Index];
        imageView.image = image;
    });
}

-(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{
//    //全局隊列(可開啓多個線程)
//    //參數:優先級(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{
//    //串行隊列
//    //參數:隊列名稱,隊列類型
//    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);//休眠一秒
//        });
//    }
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

//shareSDK異步

關鍵要用button添加事件;async




//  解決資源搶奪問題(買車票)ide

  //
//  ViewController.m
//  解決資源搶奪問題(買車票)
//
//  Created by DC020 on 15/12/25.
//  Copyright (c) 2015年 Bill. All rights reserved.
//

#import "ViewController.h"

@interface ViewController (){
    NSLock *_lock;
}

//nonatomic屬性讀取的是內存數據(寄存器計算好的結果)
//atomic屬性保持直接讀取寄存器的數據,****[這樣就不會出現一個線程正在修改數據,而另外一個線程讀取了修改以前的數據]****永遠保證同時只有一個線程在訪問一個屬性
@property(atomic,strong)NSMutableArray *tickets;//票
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    _lock =[[NSLock alloc]init];
    _tickets = [NSMutableArray array];
    [_tickets addObjectsFromArray:@[@"1.上鋪",@"2.中鋪",@"3.下鋪"]];
    [self beginSell];
}


-(void)buyTicket:(int)buyer{
    NSLog(@"%d",buyer);//10位顧客準備購買
    //使用時,把須要加鎖的代碼放在lock和unlock之間。
    //當一個線程A進入加鎖代碼後,另外一個線程B他就沒法訪問,只有當線程A執行完加鎖的任務之後,B線程才能訪問加鎖代碼
//    [_lock lock];//上鎖
    @synchronized(self){
    if(_tickets.count > 0){
        NSLog(@"%d號顧客買到:%@",buyer,[_tickets lastObject]);
        [_tickets removeLastObject];
    }
    else{
        NSLog(@"%d號顧客晚了一步,票已賣完了!!!",buyer);
    }
    }
//    [_lock unlock];//解鎖
}

-(void)beginSell{
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //建立10個線程用來搶票(10我的來買票)
    for(int i = 0; i < 10 ; i++){
        //異步執行
        dispatch_async(globalQueue, ^{
            [self buyTicket:i];
        });
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

atom

相關文章
相關標籤/搜索