天天看點

IOS學習 多線程NSThread 共享變量 賣票

#import "ViewController.h"

@interface ViewController ()

//火車票

@property (nonatomic,assign) int tickets;

@property (nonatomic,strong) NSObject *obj;

//nonatomic 非原子屬性:多個線程可同時讀取、指派

//atomic 原子屬性:多個線程下,隻有一線程可對變量指派,多個線程可同時讀取

//自旋鎖

@property (atomic,strong) NSObject *obj2;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    self.tickets = 5;

    self.obj = [[NSObject alloc] init];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(sellTicket) object:nil];

    [thread1 start];

    NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(sellTicket) object:nil];

    [thread2 start];

}

- (void)sellTicket{

    while (YES) {

        //模拟網絡延時

        [NSThread sleepForTimeInterval:1];

        //鎖是任意對象,預設鎖是開着的

        //同步鎖(互斥鎖)   自選鎖不能代替同步鎖

        @synchronized(self) {

            if (self.tickets > 0) {

                _tickets -= 1;

                NSLog(@"剩餘 %d 張票",_tickets);

                continue;

            }

            NSLog(@"票賣完了");

            break;

        }

    }

}

繼續閱讀