Swift多线程编程

//MARK:后台执行

dispatch_async(dispatch_get_global_queue(0,0), { () ->Void in

})

//MARK:主线程执行

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

})

//MARK:一次性执行

var once =dispatch_once_t()

dispatch_once(&once) { () ->Void in

}

//MARK:延迟两秒执行

let delaySecends:UInt64 = 2

let popTime = dispatch_time(DISPATCH_TIME_NOW,Int64(delaySecends *NSEC_PER_SEC))

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

}

//MARK:自定义线程

let myqueue = dispatch_queue_create("abcdef",nil)

dispatch_async(myqueue, { () ->Void in

})

//MARK:并发执行

var queueGroup = dispatch_group_create()

dispatch_group_async(queueGroup,dispatch_get_global_queue(0,0)) { () ->Void in

//线程1

}

dispatch_group_async(queueGroup,dispatch_get_global_queue(0,0)) { () ->Void in

//线程2

}

dispatch_group_notify(queueGroup,dispatch_get_global_queue(0,0)) { () ->Void in

//汇总结果

}

Example1:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

       //需要长时间处理的代码

       dispatch_async(dispatch_get_main_queue(), {

            //需要主线程执行的代码

       })

})

Example2:如果运行一系列的任务,希望当任务全部结束后运行另一个特殊的任务这种场景就是用下面的写法

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

let group = dispatch_group_create()

for(id obj in array)

dispatch_group_async(group, queue, {

self.doWork(obj)

})

dispatch_group_notify(group, queue, {

self.doneWork

})

你可能感兴趣的:(Swift多线程编程)