線程鎖,生產者與消費者

@interface ViewController ()

{

    //NSLock * lock;

    NSCondition * condition;

}

//媒介,緩衝池

@property (nonatomic, strong) NSMutableArray * array;


@end


@implementation ViewController


- (NSMutableArray *)array

{

    if (!_array)

    {

        _array = [NSMutableArray array];

    }

    return _array;

}



- (void)viewDidLoad {

    [super viewDidLoad];

    

    //創建按鈕

    

    //初始化

    condition = [[NSCondition alloc] init];

    UIButton * btn = [UIButton buttonWithType:UIButtonTypeContactAdd];

    btn.center = self.view.center;

    [self.view addSubview:btn];

    [btn addTarget:self action:@selector(_productor) forControlEvents:UIControlEventTouchUpInside];

    

    //生產與購買

    

    //通過多線程訪問這兩個方法

    for (int i = 0; i<5; i++)

    {

        [self performSelectorInBackground:@selector(_consumer) withObject:nil];

    }

    

}


//生產者

- (void)_productor

{

    [condition lock];

    [NSThread sleepForTimeInterval:.5];

    

    if (self.array.count != 0)//緩衝池中一般規定只有一個,所以做一個判斷,進來之後,什麼都不做。

    {

//        [condition wait];

    }

    else

    {

        [self.array addObject:@"產品"];

        NSLog(@"產品生產成功");

        [condition signal];//隨機喚醒一個等待的消費者

        //[condition broadcast];

    }

    

    [condition unlock];

}



//消費者

- (void)_consumer

{

    [condition lock];

    

    if (self.array.count <= 0)

    {

        NSLog(@"池子沒貨物,等待生產");

        [condition wait];//wait之後,當前線程阻塞,其他線程還可以進來

    }

    

    NSLog(@"產品購買成功");

    [self.array removeLastObject];

    //[condition signal];

    [condition unlock];

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章