1. 三種創建線程的方法 //第一種 NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(doAction) object:nil]; //線程名 thread1.nam
1. 三種創建線程的方法
//第一種
NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(doAction) object:nil];
//線程名
thread1.name = @"thread1";
//線程優先順序,0 ~ 1
thread1.threadPriority = 1.0;
//開啟線程
[thread1 start];
//第二種
//通過類方法創建線程,不用顯示的開啟start
[NSThread detachNewThreadSelector:@selector(doAction) toTarget:self withObject:nil];
//第三種
//隱式創建多線程
[self performSelectorInBackground:@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];
//就緒狀態
[thread start];
}
- (void)handleAction {
for (NSInteger i = 0 ; i < 100; i ++) {
//阻塞狀態
// [NSThread sleepForTimeInterval:2];
// [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
// NSLog(@"%@,%@",[NSThread currentThread],@(i));
//可以在子線程獲取主線程
NSLog(@"mainThread - %@",[NSThread mainThread]);
if (i == 10) {
//退出
[NSThread exit];
}
}
}
3.同步代碼塊實現買票功能
@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];
//token必須所有線程都能訪問到,一般用self
// @synchronized() {
//代碼段
// }
// NSObject * o = [[NSObject alloc] init];
//互斥鎖
@synchronized(self) {
[NSThread sleepForTimeInterval:2];
if (self.tickets > 0) {
NSLog(@"%@ 還有餘票 %@ 張",[NSThread currentThread],@(self.tickets));
self.tickets -- ;
} else {
NSLog(@"票賣完了");
break;
}
}
}
}