swift詳解之十五------------NSThread線程同步鎖

NSThread線程同步鎖


上小節用NSThread實現讀取網絡圖片 , 這節用NSThread 模擬一個賣票的例子 。用NSLock 或者NSCondition 鎖定資源

 var total = 100 //總票數
    var w1 = 0  //窗口1賣出票數
    var w2 = 0   //窗口2賣出票數
    var isSell = true  //是否出售
    var lock:NSLock?   
    var condition:NSCondition?

這裏首先定義一些變量

然後再點擊賣票的時候,開啓連個線程模仿窗口

 lock = NSLock()
        condition = NSCondition()
        //setTicketValue()
        let thread1 = NSThread(target: self, selector: "run", object: nil)
        thread1.name = "thread-1"
        thread1.start()

        let thread2 = NSThread(target: self, selector: "run", object: nil)
        thread2.name = "thread-2"
        thread2.start()


    func run(){
        while(isSell){
            lock?.lock()

            if(total>0){
                NSThread.sleepForTimeInterval(0.2);

                total--
                if(NSThread.currentThread().name == "thread-1")
                {
                    w1++
                }else if(NSThread.currentThread().name == "thread-2"){
                    w2++
                }
                dispatch_async(dispatch_get_main_queue()) {

                    self.setTicketValue()
                }

            }else{

                dispatch_async(dispatch_get_main_queue()) {

                    self.totalTicks.text = "票賣完啦"
                    self.isSell = false
                }

            }

            lock?.unlock()
        }
    }

這裏寫圖片描述

大概就是這樣的一個小示例 。
源碼下載地址:源碼

學習iOS,有他就夠了,小碼哥視頻,傳智、黑馬、各種swift書籍

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章