zyme000 2015-11-08 09:02 采纳率: 40%
浏览 2321

iOS中 @synchronized(对象) 中"对象"是什么的问题

@synchronized(对象)中的这个"对象"是什么,锁定它是为了什么
在 sellTicket 中锁定了 self , 如果在 ticket 中没有用@synchronized(self),就会在sellTicket中线程运行的情况下,运行ticket中的线程,
如果用了@synchronized(self) 所有线程就会一个一个运行

//============== 代码部分 =================
@property (nonatomic, assign) NSInteger ticket;

  • (void)viewDidLoad {
    [super viewDidLoad];

    _ticket = 50;

    [NSThread detachNewThreadSelector:@selector(sellTicket) toTarget:self withObject:nil];
    [NSThread detachNewThreadSelector:@selector(sellTicket) toTarget:self withObject:nil];

    [NSThread detachNewThreadSelector:@selector(ticket123) toTarget:self withObject:nil];

    [NSThread detachNewThreadSelector:@selector(sellTicket) toTarget:self withObject:nil];
    [NSThread detachNewThreadSelector:@selector(sellTicket) toTarget:self withObject:nil];

}

  • (void)sellTicket{

    while (_ticket > 0) {

    [NSThread sleepForTimeInterval:3];
    
    @synchronized (self){   
    
        if (_ticket > 0) {
            NSLog(@"123");
            [NSThread sleepForTimeInterval:3];
            self.ticket--;
            NSLog(@"%@  %ld ", [NSThread currentThread], _ticket);
    
        }
    }
    

    }
    }

  • (void)ticket123 {

    // @synchronized (self) {
    for (int i = 0; i < 10; i++) {

        [NSThread sleepForTimeInterval:1];
        self.ticket--;
        NSLog(@"ticker %ld", _ticket);
    }
    

    }

}

  • 写回答

1条回答 默认 最新

  • mifit 2015-11-10 01:12
    关注

    @synchronized(对象)中的这个"对象"是什么?
    对象可以是OC的任何对象。

    锁定它是为了什么?
    防止多个线程同时访问这个对象。相当于加锁。

    评论

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求