多线程—NSThread实现生产消费模型。

利用NSMutableArray以及NSCondition实现了类似java中的阻塞队列,用于生产消费模型。

以下为例子:

@interface Text ()

@property (nonatomic,strong)NSThread *thread;

@property (nonatomic,strong)NSCondition *threadSign;

@property (nonatomic,strong)NSLock *lock;//当对array进行相同操作的时候,需要锁住资源。比如同时删除。

@property (nonatomic,strong)NSMutableArray<NSNumber *> *MutableArray;//这里没必要用atomic,因为利用上面2个属性就可以把Array实现成一个类似JAVA里的阻塞队列。

@end

@implementation Text

-(instancetype)init {

    if (self = [super init]) {

        self.thread = [[NSThread allocinitWithTarget:self selector:@selector(run) object:nil];

        self.threadSign = [[NSCondition allocinit];

        self.lock = [[NSLock allocinit];

        self.MutableArray = [[NSMutableArray allocinit];

        [NSTimer scheduledTimerWithTimeInterval:1 target:selfselector:@selector(start) userInfo:nil repeats:NO];

    }

    return self;

}


- (void)start {

    [self.thread start];

    int i = 0;

    int data;

    while (i<=30) {

        

        if (self.MutableArray.count >= 10) {

            [self.lock lock];

            [self.MutableArray removeObjectAtIndex:0];

            [self.lock unlock];

        }

        

        

        data = rand()%10;

        NSNumber *num = [NSNumber numberWithInt:data];

        [self.threadSign lock];

        [self.MutableArray insertObject:num atIndex:0];//生产:新的数据每次放在array的第一个元素

        [self.threadSign signal];//不管array为空还是不为空,只要有数据来,就唤醒第二个线程

        [self.threadSign unlock];

        NSLog(@"线程1——%iarray大小——%lu",data,(unsignedlong)self.MutableArray.count);

        i++;

    }

    [self.thread cancel];

    [self.MutableArray removeAllObjects];//记得清理Array

}


- (void)run {

    while (![self.thread isCancelled]) {

        if (self.MutableArray.count == 0) {

            [self.threadSign lock];

            [self.threadSign wait];//Array为空时,就等待。

            [self.threadSign unlock];

        }

        int data = [[self.MutableArray lastObjectintValue];

        [self.lock lock];

        [self.MutableArray removeLastObject];//消费:删除最后一个元素

        [self.lock unlock];

        NSLog(@"线程2——%iarray大小——%lu",data,(unsignedlong)self.MutableArray.count);

    }

}


@end


结果显示中,array的大小总为1,2。则表明消费速度跟得上生产速度。基本生产一个数据,就能消费掉一个数据。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值