线程锁,生产者与消费者

@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];

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值