Swift中多線程和異步任務

//創建GCD隊列(全局的)

        let myQueue : dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

        //用異步的方式運行隊列裏地任務

        dispatch_async(myQueue, { () -> Void in

            sleep(5)

            

            //在主線程中更改UI

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                self.myLabel.text = "hahahahaha"

            })

            

        })


        

        //自定義GCD

        let myQueue : dispatch_queue_t = dispatch_queue_create("com.gyl.threads", DISPATCH_QUEUE_CONCURRENT)

        //用異步方式運行隊列裏地任務

        dispatch_async(myQueue, { () -> Void in

            sleep(5)

            

            //在主線程中更新程序

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                self.myLabel.text = "hahahahaha"

            })

        })


 //延遲時間的設置

        let time:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, (Int64)(NSEC_PER_MSEC * 2))

        //延遲

        dispatch_after(time, dispatch_get_main_queue()) { () -> Void in

            self.myLabel.text = "請點擊調用按鈕"

        }

        

        //比較耗時重複次數不多的地方使用的

        //循環

        dispatch_apply(3, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { (UInt index) -> Void in

                print(index)

        }

        




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