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;
}
}
}
}