IOS multithreading is first seen, and ios Multithreading
1. Three ways to create a thread
// First
NSThread * thread1 = [[NSThread alloc] initWithTarget: self selector: @ selector (doAction) object: nil];
// Thread name
Thread1.name = @ "thread1 ";
// Thread priority, 0 ~ 1
Thread1 threadpriority = 1.0;
// Enable the thread
[Thread1 start];
// Type 2
// Create a thread by using the class method and enable start without displaying
[NSThread detachNewThreadSelector: @ selector (doAction) toTarget: self withObject: nil];
// The third type
// Create multiple threads implicitly
[Self defined mselectorinbackground: @ selector (doAction :) withObject: nil];
@ Implementation ViewController
-(Void) viewDidLoad {
[Super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog (@ "mainThread-% @", [NSThread mainThread]);
NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (handleAction) object: nil];
// Ready
[Thread start];
}
-(Void) handleAction {
For (NSInteger I = 0; I <100; I ++ ){
// Blocking status
// [NSThread sleepForTimeInterval: 2];
// [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow: 2];
// NSLog (@ "% @, % @", [NSThread currentThread], @ (I ));
// You can obtain the master thread from the subthread.
NSLog (@ "mainThread-% @", [NSThread mainThread]);
If (I = 10 ){
// Exit
[NSThread exit];
}
}
}
3. Synchronize code blocks to implement the ticket buying Function
@ Implementation ViewController
-(Void) viewDidLoad {
[Super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Self. tickets = 20;
NSThread * thread1 = [[NSThread alloc] initWithTarget: self selector: @ selector (saleTicket) object: nil];
// Thread1.name = @ "computer ";
[Thread1 start];
NSThread * thread2 = [[NSThread alloc] initWithTarget: self selector: @ selector (saleTicket) object: nil];
// Thread2.name = @ "phone ";
[Thread2 start];
}
-(Void) saleTicket {
While (1 ){
// [NSThread sleepForTimeInterval: 1];
// The token must be accessible to all threads. self is generally used.
// @ Synchronized (){
// Code segment
//}
// NSObject * o = [[NSObject alloc] init];
// Mutex lock
@ Synchronized (self ){
[NSThread sleepForTimeInterval: 2];
If (self. tickets> 0 ){
NSLog (@ "% @ remaining votes % @ Zhang", [NSThread currentThread], @ (self. tickets ));
Self. tickets --;
} Else {
NSLog (@ "tickets sold out ");
Break;
}
}
}
}