fengsh998 Original address: http://blog.csdn.net/fengsh998/article/details/30354127 reprint please indicate the source
Swift does not use a new set of threads, using a set of threads from the OC source. The following example illustrates the use of threads in Swift.
Its use includes common: NSTHREAD,NSOPERATIONQUEUE,GCG
Import UIKit class Swiftthreaddemo:uiviewcontroller {var queue = Nsoperationqueue ()//init ()//{ Alloc//Super.init ()//} deinit {//dealloc} func Test Gcdthread () {Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), { Write here code that takes a lot of time for var i = 0; I < 100000; i++ {println ("GCD thread running.") } sleep (5); Dispatch_async (Dispatch_get_main_queue (), {//Here return the main thread, write code that requires the main thread to execute println ("Here return the main thread, write the required The main thread executes the Code ")})}} func Testnsthread () {//mode one//NSTH Read.detachnewthreadselector ("Threadinmainmethod:", Totarget:self,withobject:nil)//mode two var MyT Hread = Nsthread (target:self,selector: "Threadinmainmethod:", Object:nil) Mythread.start ()} func Threadinmainmethod (sender:anyobject) {for var i = 0; I < 100000; i++ {println ("Nsthread running.") } sleep (5); println ("Nsthread over.") } func Testnsoperationqueue () {//func (op:nsoperation!) var mopt = Myoperationthread () queue.addoperation (MOPT)}} class Myoperationthread:nsoperation { Override func Start () {Super.start ()} override func Main () {for var i = 0; I < 100000; i++ {println ("nsoperation running.") } println ("Nsoperation over.") } }
Call:
var st = Swiftthreaddemo () st.testnsthread () sleep (2) st.testgcdthread () St.testnsoperationqueue ( )
[Love Swift] Day9: A tentative study of Swift language (threading)