zoukankan      html  css  js  c++  java
  • IOS NSThread(线程同步)

    @interface HMViewController ()
    /** 剩余票数 */
    @property (nonatomic, assign) int leftTicketsCount;
    @property (nonatomic, strong) NSThread *thread0;
    @property (nonatomic, strong) NSThread *thread1;
    @property (nonatomic, strong) NSThread *thread2;
    @end
    
    @implementation HMViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        // 默认有100张
        self.leftTicketsCount = 100;
        
        // 开启多条线程同时卖票
        self.thread0 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
        self.thread0.name = @"售票员 A";
    //    self.thread0.threadPriority = 0.0;
        
        self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
        self.thread1.name = @"售票员 B";
    //    self.thread1.threadPriority = 1.0;
        
        self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
        self.thread2.name = @"售票员 C";
    //    self.thread2.threadPriority = 0.0;
    }
    
    /**
     * 卖票
     */
    - (void)saleTicket
    {
        while (1) {
            @synchronized(self) { // 加锁(只能用一把锁)
                // 1.先检查票数
                int count = self.leftTicketsCount;
                if (count > 0) {
                    // 暂停
    //                [NSThread sleepForTimeInterval:0.0002];
                    
                    // 2.票数 - 1
                    self.leftTicketsCount = count - 1;
                    
                    NSThread *current = [NSThread currentThread];
                    NSLog(@"%@ 卖了一张票, 剩余%d张票", current.name, self.leftTicketsCount);
                } else {
                    // 退出线程
                    [NSThread exit];
                }
            } // 解锁
        }
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        [self.thread0 start];
        [self.thread1 start];
        [self.thread2 start];
    }
  • 相关阅读:
    Cg:访问OpenGL的状态
    C++ Exception Handling
    C语言的调用规约(Calling Convension)之参数传递和返回值
    Why is FBX readonly in animation editor when imported?
    如何在Visual Studio中编译wxWidgets
    ICU字符集编码转换一例
    VisTools
    关于数值分析和LCP问题的一些开源项目
    C++: The Case Against Global Variables
    老男孩筷子兄弟
  • 原文地址:https://www.cnblogs.com/liuwj/p/6602084.html
Copyright © 2011-2022 走看看