[多线程之一]-NSThread银行取款问题

//
//  ViewController.h
//  银行取款问题
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
- (IBAction)DrawBtn:(UIButton *)sender;


@end

@interface Account : NSObject

@property(nonatomic, copy)NSString* AccountNo;
//atomic属性里面加了锁了,禁止多线程同时修改。
@property(nonatomic, assign, readwrite)CGFloat Balance;

-(instancetype)initWithAccountNo:(NSString*)ANo
                         Balance:(CGFloat)ABalance;
-(void)draw:(CGFloat)AdrawAccount;

@end
//
//  ViewController.m
//  银行取款问题

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

{
    Account* a;
    NSThread* t1;
    NSThread* t2;
    NSLock* lock;
}
- (void)viewDidLoad {
    a = [[Account alloc] initWithAccountNo:@"12345" Balance:100];
    lock = [[NSLock alloc] init];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)drawMethod:(NSNumber*)ADrawAccount
{
    @synchronized(a)//方法1
    {
       [a draw:[ADrawAccount doubleValue]];
    }
    
    [lock lock];//方法2
       [a draw:[ADrawAccount doubleValue]];
    [lock unlock];
}

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

- (IBAction)DrawBtn:(UIButton *)sender {
    t1 = [[NSThread alloc] initWithTarget:self selector:@selector(drawMethod:) object:[NSNumber numberWithInt:80]];
    t2 =[[NSThread alloc] initWithTarget:self selector:@selector(drawMethod:) object:[NSNumber numberWithInt:80]];
    //注意:如果把t1和t2放到viewdidload里面定义的话,会出错,原因是线程执行完了,属于finish状态了,就不能再执行了。
    [t1 start];
    [t2 start];
}
@end

@implementation Account

-(instancetype)initWithAccountNo:(NSString *)ANo Balance:(CGFloat)ABalance
{
    if (self = [super init]) {
        self.AccountNo = ANo;
        _Balance = ABalance;
    }
    return self;
}

-(void)draw:(CGFloat)AdrawAccount
{
    //atomic特性没验证出来,以后再说吧。
    if (self.Balance > AdrawAccount) {
        [NSThread sleepForTimeInterval:0.1];//为了试验余额为负数,特此加了延迟。妥妥复现。
        self.Balance = self.Balance - AdrawAccount;
        NSLog(@"%@取款成功,取款金额%f",[NSThread currentThread].name,AdrawAccount);
        NSLog(@"账户%@,余额为:%f", self.AccountNo,_Balance);
    }
    else
    {
        NSLog(@"%@取款失败,余额不足!",[NSThread currentThread].name);
    }
}

@end
摘自《疯狂iOS》下册。

你可能感兴趣的:(多线程,NSThread)