IOS Multi-thread nsthread simple to use

Source: Internet
Author: User

1. Thread Building and opening:

(1) _thread1 = [[Nsthread alloc]initwithtarget:self selector: @selector (Threadonemethod) Object:nil];    _thread2 = [[Nsthread alloc]initwithtarget:self selector: @selector (Threadtwomethod) Object:nil];        [_thread1 start];    [_thread2 start];
Build first, then turn on, the advantage is that you can control the time to open, and you can get the Nsthread object, easy to communicate with this thread later.
  (2) [Nsthread detachnewthreadselector: @selector (Threadonemethod) totarget:self Withobject:nil];  (3) [Self Performselectorinbackground: @selector (Threadonemethod) Withobject:nil];
Another is to inherit a subclass from the system's Nsthread, which is built like the parent class, but the code executed inside the thread is written in the-(voidthe Main method inside:
@interface Mythread:nsthread//Inherit from Nsthread @end////////////////////-(void) main{for    (int i = 0; i<10; i++) {        NSLog (@ "MyThread count:%d", i);        Sleep (1);    }    NSLog (@ "thread End");} Use the custom thread object _thread3 = [[MyThread alloc]init];    [_thread3 start];
In contrast, the threads that were built in the previous 3 methods are all within the current class file, and the main function, which is the thread object itself, can be used in any other place where the thread method needs to be used, rather than implementing one method at a time.


2, thread synchronization, that is, the use of the thread Lock:

(1) @synchronized Keywords:  

-(void) threadonemethod{    @synchronized (@ "lock") {for          (int i= 0; i<10; i++) {//Loop 10 times, one identity per output, and then thread sleeps for one second            NSLog (@ "111");            Sleep (1);         }    }    NSLog (@ "Thread1 end");} -(void) threadtwomethod{    @synchronized (@ "lock") {        for (int i= 0; i<5; i++) {//Loop 5 times, Each time an identity 222 is output, and then the thread sleeps for 1 seconds            NSLog (@ "222");            Sleep (1);        }    }    NSLog (@ "Thread2 end");}
The above example is a combination of the first thread-building method, two threads almost simultaneously open, but the first one faster, after the effect is that the first method loop output 10 times "111" After the end, the second method output "222". Because the first method begins to enter@synchronized(@ "Lock"after that, the second method executes to the @synchronized(@ "lock") and will not go in here until a previous thread comes out of it before it can continue down, This is the role of the thread lock. There are times when multiple threads operate with the same data or object at the same time, and there can be unexpected bad situations where a thread lock is used to keep threads safe while other threads are unable to operate.

@synchronized(@ "lock") is distinguished by using the object in parentheses, and if the object in the second method is changed, it becomes @synchronized(@ "111111"), will not play the role of the lock, because it is that they are two completely unrelated locks.

2, Nslock:

[_lock lock];        for (int i= 0; i<10; i++) {            NSLog (@ "111");            Sleep (1);        } [_lock unlock];
The core method part is no different, just replace the lock with [_lock lock] ... [_lock unlock]; the lock here is based on the _lock Nslock object, which means that when a Nslock object calls the Lock method, the other threads use the samethe Nslock object calls the Lock method and then stagnates, knowing that the same Nslock object calls the Unlock method again.

This process is a bit like some physical examination items, the room at the same time can only check a person, a person in the door will be locked, then there are other people can only wait, wait until the people inside, the door open, the next to go in.


3. Communication between Threads:

The secondary thread sends a message to the main thread:

[Self Performselectoronmainthread: @selector (Mainthreadmethod) Withobject:nil Waituntildone:no];

Self is the method's caller,Mainthreadmethod is the method that lets the main thread call , and then this method can take parameters, that is, object, the last Waituntildone is whether to wait until the main thread to execute the method, This performselector method only returns.

To send a message to any other thread:
[Self performselector: @selector (timerfire) onthread:_thread1 Withobject:nil Waituntildone:no];
The main point here is to pass in a Nsthread object to specify which thread to execute, which is also the meaning of preserving the thread object when the thread is built earlier.

It is important to note, then, that these performselector form methods require the runloop of the other thread to be turned on, because these methods are essentially runloop input sources, sending messages to the runloop of the other thread, Then the other party obtains the message from the Runloop, only then executes the method. The runloop of the main thread is turned on by default, and the Runloop of the secondary thread is built by default, but it needs to be turned on manually.

4. Thread Shutdown:

to close a thread, you can send a message to the thread to close it:

-(Ibaction) Killthread: (UIButton *) Sender {    [self performselector: @selector (exitthread:) onthread:_thread1 Withobject:_thread1 Waituntildone:no];} -(void) ExitThread: (Nsthread *) thread{    NSLog (@ "Thread EXIT1");    [Nsthread exit];    NSLog (@ "Thread EXIT2");}
You can also:
<span style= "FONT-SIZE:14PX;" >-(void) threadonemethod{//Front Write threads need to execute the code of the task, and finally go into the Runloop loop, keeping the thread not ending while maintaining the receiving message nsrunloop *therl = [Nsrunloop curren    Trunloop]; while (shouldkeeprunning) {//through </span><span style= "font-family:arial, Helvetica, Sans-serif;" ><span style= "FONT-SIZE:12PX;" >shouldkeeprunning determines whether or not to continue the loop, if no, it stops the loop and then continues to run down, and the thread ends </span></span><span style= "Font-size : 14px; "        > NSLog (@ "Looprun");    [Therl Runmode:nsdefaultrunloopmode beforedate:[nsdate distantfuture];    }; NSLog (@ "Thread1 end");} BOOL shouldkeeprunning = yes;//a global bool type variable-(ibaction) Killthread: (UIButton *) Sender {//click button, modify </span ><span style= "font-family:arial, Helvetica, Sans-serif;" ><span style= "FONT-SIZE:12PX;" >shouldkeeprunning for No</span></span><span style= "FONT-SIZE:14PX;"    > shouldkeeprunning = NO; }</span>
Here is the change of a global variable to control whether the thread continues or ends. One small problem, however, is that when a thread's Runloop accepts a foreign input source, such as another thread call:
[Self performselector: @selector (timerfire) onthread:_thread1 Withobject:nil Waituntildone:no];
When this thread runs, Runloop receives the message and blocks it in the method[TherlRunMode:NsdefaultrunloopmodeBeforedate:[NSDateDistantfuture] ] Inside, that is, the while loop will not continue to the next loop, then changeShouldkeeprunning can't get feedback right away, so we need to use:
BOOL shouldkeeprunning = yes;-(ibaction) Killthread: (UIButton *) Sender {    [self performselector: @selector ( ExitThread:) onthread:_thread1 withobject:nil waituntildone:no];    } Union-(void) ExitThread: (Nsthread *) thread{    shouldkeeprunning = NO;}
This is to send a message to the thread that is being closed, which immediately wakes the target thread's runloop, because[TherlRunMode:Nsdefaultrunloopmode Beforedate:[NSDate Distantfuture] ] method is characterized in that the method returns immediately after exposure to the input source, so that the while loop enters into the next loop immediately, and the loop condition is judged, and then because Shouldkeeprunning becomes no, it exits the loop and the thread ends.

Two kinds of thread end methods, it seems that the second more natural, specific to the internal operation of the thread and memory management impact, but also to study.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.