Nsthread
//1. Create a threadNjthread *thread = [[Njthread alloc] initwithtarget:self selector: @selector (Demo:)Object:@"LNJ"]; //set the thread name[Thread SetName:@"XMG"]; //set the priority of a thread//priority only indicates a greater likelihood of being called by the CPU[Thread SetThreadPriority:1.0]; //2. Start the thread[Thread start];
// get the main thread // Is the main thread // get current thread Nsthread *current = [Nsthread CurrentThread]; // the name of the thread -(void) SetName: (NSString *) n; -(NSString *) name;
- Other ways to create threads
- Advantages: Simple and fast
- Cons: Unable to set the thread in more detail
// 1.创建线程
[Nsthread Detachnewthreadselector: @selector (Demo:) totarget:self withobject:@ "lnj"];
// 1.创建线程// 注意: Swift中不能使用, 苹果认为这个方法不安全
[Self Performselectorinbackground: @selector (Demo:) Withobject:@ "lnj"];
Start Thread -(void) start; // go to Ready status, run status. When the thread task finishes executing, automatically enters the death state to block (pause) the thread + (void) Sleepuntildate: (NSDate *) date; + (void) Sleepfortimeinterval: (Nstimeinterval) ti; // Enter blocking State Force Stop thread + (void) exit; // into the state of death
注意:一旦线程停止(死亡)了,就不能再次开启任务
// code that needs to be locked }
Advantages and disadvantages of mutual exclusion lock: can effectively prevent the data security problem caused by multi-thread snatch resources disadvantage: the need to consume a lot of CPU resources
Mutual exclusion Lock attention point
- Lock 1 copies of code with only 1 locks, with multiple locks is not valid
- The larger the locking range, the worse the performance
- Inter-thread communication
- Child threads do time-consuming operations, the main thread updates the data
[Self performselectorinbackground: @selector (download) withobject:nil]; /* Whether the Waituntildone waits for the invoked method to complete, it is possible to wait for the calling method to complete! YES: Wait for the called thread to finish executing and then execute the following code No: You can execute the following code without waiting for the called thread to execute */[Self performselectoronmainthread: @selector (showImage:) Withobject:[uiimage Imagewithdata:data] Waituntildone:yes];
Multithreading--Nsthread