移动开发

iOS锁-@synchronized

2018-07-13  本文已影响4人  口子窖

@synchronized

先上例子

#import <Foundation/Foundation.h>
@interface NSLockTest : NSObject
- (void)forTest;
@end
#import "NSLockTest.h"
@interface NSLockTest()
@property (nonatomic,strong) NSArray *tickets;
@property (nonatomic,assign) int soldCount;
@end
@implementation NSLockTest
- (void)forTest
{
    self.tickets = @[@"南京-北京A101",@"南京-北京A102",@"南京-北京A103",@"南京-北京A104",@"南京-北京A105",@"南京-北京A106",@"南京-北京A107",@"南京-北京A108",@"南京-北京A109",@"南京-北京A110",@"南京-北京A111",@"南京-北京A112",@"南京-北京A113",@"南京-北京A114",@"南京-北京A115",@"南京-北京A116",@"南京-北京A117",@"南京-北京A118",@"南京-北京A119",@"南京-北京A120",@"南京-北京A121",@"南京-北京A122",@"南京-北京A123",@"南京-北京A124",@"南京-北京A125",@"南京-北京A126",@"南京-北京A127",@"南京-北京A128",@"南京-北京A129",@"南京-北京A130"];
    //第一窗口
    NSThread *windowOne = [[NSThread alloc] initWithTarget:self selector:@selector(soldTicket) object:nil];
    windowOne.name = @"一号窗口";
    [windowOne start];
    //第二窗口
    NSThread *windowTwo = [[NSThread alloc] initWithTarget:self selector:@selector(soldTicket) object:nil];
    windowTwo.name = @"二号窗口";
    [windowTwo start];
    //第三窗口
    NSThread *windowThree = [[NSThread alloc] initWithTarget:self selector:@selector(soldTicket) object:nil];
    windowThree.name = @"三号窗口";
    [windowThree start];
    //第四窗口
    NSThread *windowFour = [[NSThread alloc] initWithTarget:self selector:@selector(soldTicket) object:nil];
    windowFour.name = @"四号窗口";
    [windowFour start];
}
-(void)soldTicket
{
    @synchronized (self) {
        if (self.soldCount == self.tickets.count) {
            NSLog(@"=====%@ 剩余票数:%lu",[[NSThread currentThread] name],self.tickets.count-self.soldCount);
            return;
        }
        //延时卖票
        [NSThread sleepForTimeInterval:0.2];
        self.soldCount++;
        NSLog(@"=====%@ %@ 剩%lu",[[NSThread currentThread] name],self.tickets[self.soldCount-1],self.tickets.count-self.soldCount);
        
    }
    //一直卖票
    [self soldTicket];
}
@end

注意

1、本质上@synchronized应该是一个互斥锁

2、据说比较耗时,这个没有统计过

3、@synchronized (锁住的对象) {代码块}

4、重复加锁无额外效果

5、@synchronized (nil) {代码块},不会起任何作用。

上一篇 下一篇

猜你喜欢

热点阅读