欢迎光临
我们一直在努力

NSCondition多线程

建站超值云服务器,限时71元/月

NSCondition多线程

项目介绍:

使用NSCondition控制线程同步通信:NSCondition 可以让那些已经锁定的NSCondition对象却无法继续使用执行的线程释放NSCondition对象,NSCondition对象也可以唤醒其他处于等待状态的线程;

-wait :导致线程当前线程一直等待,直到其他线程调用NSCondition的signal方法或broadcast方法唤醒该线程,waitUntilDtae:

-signal:唤醒等待的单个线程;选择是任意性的,

-broadcast:唤醒所有线程;

#import "Acount.h"

@implementation Acount
-(instancetype)init
{
    self=[super init ];
    if (self) {
        _cond=[NSCondition new];
    }
    return self;
}

-(instancetype)initWithCountNo:(NSString *)acountNo balance:(float)balance
{
    self=[super init];
    if (self) {
        _cond=[NSCondition new];
        _acountNo=acountNo;
        _balance=balance;
        
    }
    return self;
}
-(void)draw:(float)drawNum
{
    [_cond lock];
    //flag=no没钱取钱阻塞;
    if (drawNum>_balance) {
        _flag=NO;
    }
    else
    {
        _flag=YES;
    }
    if (!_flag) {
        NSLog(@"等待存钱drawNum:%f,_balance:%f",drawNum,_balance);
        [_cond wait];
        
    }else
    {
        
        NSLog(@"%@取钱:%g", [NSThread currentThread].name,drawNum);
        _balance-=drawNum;
        NSLog(@"账户余额:%g",_balance);
        [_cond broadcast];
    }
    [_cond unlock];
}
-(void)deposit:(float)depositNum
{
    [_cond lock];
  
         NSLog(@"%@存钱:%g", [NSThread currentThread].name,depositNum);
        _balance+=depositNum;
          NSLog(@"账户余额:%g",_balance);
        [_cond broadcast];
   
    [_cond unlock];
   
}
===============================================================================================================================
- (void)viewDidLoad {
    [super viewDidLoad];
    _account=[[Acount alloc]initWithCountNo:@"123" balance:1000.0];

}
- (IBAction)DepositAndDraw:(id)sender {
    [NSThread detachNewThreadSelector:@selector(drawMethod:) toTarget:self withObject:[NSNumber numberWithDouble:800.0]];
    [NSThread detachNewThreadSelector:@selector(drawMethod:) toTarget:self withObject:[NSNumber  numberWithDouble:800.0]];
    [NSThread detachNewThreadSelector:@selector(drawMethod:) toTarget:self withObject:[NSNumber  numberWithDouble:800.0]];
    [NSThread detachNewThreadSelector:@selector(depositMethod:) toTarget:self withObject:[NSNumber  numberWithDouble:800.0]];

}
-(void)depositMethod:(NSNumber*)depositNum
{
    [NSThread currentThread].name=@"A存钱";
    for (int i=0; i<100; i++) {
        [_account deposit:[depositNum floatValue]];
    }
}
-(void)drawMethod:(NSNumber*)drawNum
{
     [NSThread currentThread].name=@"B取钱";
    for (int i=0 ; i<100; i++) {
        [_account draw:[drawNum floatValue]];
    }
}



test.zip
(68.21 KB, 下载次数: 215)

2017-1-3 10:22 上传
点击文件名下载附件

多线程银行账户

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » NSCondition多线程
分享到: 更多 (0)