One: Create threads,nsthread Three ways to create threads commonly:
//1: Create a startup manuallyLet Thread:nsthread = Nsthread (target:self, selector:"dosomething:",Object:"param") Thread.Name="ChildThread1" //How to manually create a thread you can set the name of a threadThread.Start ()//2: Create complete auto startNsthread.detachnewthreadselector ("dosomething:", Totarget:self, Withobject:"param") //3 Creating an automatic start implicitlySelf.performselectorinbackground ("dosomething:", Withobject:"param")
Two: Nsthread common functions
// 1. Get the main thread nsthread.mainthread ( )//2. Get Current threads Nsthread.currentthread () //3. Thread Sleep Nsthread.sleepfortimeinterval (< #T # #ti : nstimeinterval# #NSTimeInterval #>) nsthread.sleepuntildate (< #T # #date: nsdate# #NSDate #> )
Three: Thread synchronization and Thread safety
Thread synchronization: Prevent multiple threads from seizing data security issues caused by unified resources // Lock code blocks to ensure thread safety lock: Nslock = Nslock () lock. Lock () //something lock. Unlock ()
Four: inter-thread communication
//ensure thread safety, return to the main thread after the child thread finishes updating UI Waituntildone indicates whether to wait for completion, and if true, after the main thread completes the operation, execute the following codeSelf.performselectoronmainthread ("dosomething", Withobject:"param", Waituntildone:false) //If you are updating only a single control, you can use the following simpler method, such as setting a pictureLet imageview:uiimageview=Uiimageview () imageview.performselectoronmainthread ("setimage:", Withobject:uiimage (), Waituntildone:false)
V: Thread-deferred execution
// deferred Execution (note, deferred execution do not use thread sleep to implement, blocking the current thread) Self.performselector ("dosomething:" "param"3)
Finish!
iOS development: Nsthread multi-threaded use