// Initialize Lock Object Ticketcondition = [[Nscondition alloc] init]; // Start the first thread. Ticketsthreadone = [[nsthread alloc] initwithtarget: Self selector: @ selector (run) Object : Nil]; [ticketsthreadone setname: @" Thread-1 " ]; [Ticketsthreadone start]; // Start the second thread. Ticketsthreadtwo = [[nsthread alloc] initwithtarget: Self selector: @ selector (run) Object : Nil]; [ticketsthreadtwo setname: @" Thread-2 " ]; [Ticketsthreadtwo start]; -( Void ) Run { While (True ){ // Lock [Ticketscondition Lock ]; // Dosomething .. [Ticketscondition unlock];} // Release resources. -( Void ) Dealloc {[ticketsthreadone release]; [ticketsthreadtwo release]; [ticketscondition release]; [Super dealloc];} // When a thread is running, it may need to communicate with other threads, such as modifying the interface in the main thread. You can use the following interface: -( Void ) Performselecw.mainthread :( SEL) aselector withobject :( ID ) Arg waituntildone :( bool) wait such as: [self authentication mselecw.mainthread: @ selector (updateui) withobject: Nil waituntildone: No]; // Updateui is the method name exchanged with the UI. // Enable the nyothoreleasepool.
Use another method to create a subthread:
// The nsthread class is used. Here we use detachnewtheadselector: totagaet: withobject to create a thread. // Function setupthread :( nsarray *) userinfor. Use userinfor to upload the required data to the thread. // Function Definition: -( Void ) Setupthread :( nsarray * ) Userinfor {[nsthread detachnewthreadselector: @ selector (threadfunc :) totarget: Self withobject :( ID ) Userinfor];
// Note that threadfunc is followed by a colon. The threadfunc method carries the ID parameter.} -( Void ) Threadfunc :( ID ) Userinfor {ngutoreleasepool * Pool = [[NSAID utoreleasepool alloc] init]; // .... The processing that needs to be done. // Return immediately after the thread ends. [Self defined mselecw.mainthread: @ selector (endthread) withobject: Nil waituntildone: No]; [pool release];} // Performselectoronmainthread notifies the main thread to execute the function endthread. You can also use javasmselector: onthread: withobject: waituntil to notify a thread of processing after the execution thread ends. // Do not refresh the interface within the thread. If you need to refresh the interface, call out the methods in the main thread to refresh through performselecdomainmainthread.