/// 隐式创建
// @interface NSObject (NSThreadPerformAdditions),给NSObject拓展了分类方法
// 方便程序员可以很方便的调用跟线程相关的方法
- (void)threadDemo3
{
[selfperformSelectorInBackground:@selector(demo:)withObject:@"perform"];
}
/// 类方法创建
- (void)threadDemo2
{
// detach : 分离,分离出一个新的线程,并且指定线程执行的方法
// 无法获取到线程对象
// 这个方法会自动的启动子线程执行
[NSThreaddetachNewThreadSelector:@selector(demo:)toTarget:selfwithObject:@"detach"];
}
/// 对象方法创建
- (void)threadDemo1
{
// 创建线程对象
NSThread *thread = [[NSThreadalloc] initWithTarget:selfselector:@selector(demo:)object:@"alloc"];
// 启动子线程
[thread start];
}
/// 执行线程执行的方法
- (void)demo:(id)param
{
// 查看当前线程
NSLog(@"%@ %@",param,[NSThreadcurrentThread]);
}
- (void)threadDemo
{
// 创建线程对象 : 新建状态
NSThread *thread = [[NSThreadalloc] initWithTarget:selfselector:@selector(demo)object:nil];
// 就绪状态
[thread start];
}
/// 制定新线程执行的方法
- (void)demo
{
for (int i =0; i < 5; i++) {
NSLog(@"%d %@",i,[NSThreadcurrentThread]);
// 休眠 : 使当前线程休眠
[NSThreadsleepForTimeInterval:1.0];
// 休眠到制定的日期
if (2 == i) {
[NSThreadsleepUntilDate:[NSDatedateWithTimeIntervalSinceNow:2.0]];
}
// 强制退出线程
if (3==i) {
NSLog(@"begin");
// exit : 可以使当前线程退出
[NSThread exit];
NSLog(@"end");
}
}
NSLog(@"over");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 查看当前的线程.线程占512KB
NSLog(@"主 %tu",[NSThreadcurrentThread].stackSize/1024);
[selfthreadDemo];
}
- (void)threadDemo
{
// 线程1
NSThread *thread1 = [[NSThreadalloc] initWithTarget:self selector:@selector(demo) object:nil];
// 设置线程的name属性,可以追踪线程,定位BUG
thread1.name = @"t1";
//设置优先级,范围是0.0~1.0,最高是1.0.默认是0.5
// 决定的是线程有更多的机会被CPU调度执行,并不是决定的线程执行的先后顺序
thread1.threadPriority = 1.0;
[thread1 start];
// 线程2
NSThread *thread2 = [[NSThreadalloc] initWithTarget:self selector:@selector(demo) object:nil];
thread2.name = @"t2";
thread2.threadPriority = 0.0;
[thread2 start];
}
- (void)demo
{
// 查看当前的线程
NSLog(@"%@",[NSThreadcurrentThread]);
// %tu NSUInteger的占位符,可以适配NSUInteger的32位设备和64位设备
// 32位设备,NSUInteger,是无符号的int.无符号表示没有有正负数
// 64位设备,NSUInteger,是无符号的long.
// %zd NSInteger的占位符,可以适配NSInteger的32位设备和64位设备
// 32位设备,NSInteger,是有符号的int.有符号表示可以有正负数
// 64位设备,NSInteger,是有符号的long.
NSLog(@"子 %tu",[NSThreadcurrentThread].stackSize/1024);
for (int i =0; i < 5; i++) {
NSLog(@"%d %@",i,[NSThreadcurrentThread]);
// int num = 0;
// int a = 5/num;
}
}
//先进来的线程会把操作执行完成,才能让其他线程执行
// @synchronized(self) {
while (YES) {
// 互斥锁/同步锁,使用了线程同步技术
// 特点 :能够保证被锁定的代码,同一时间,只有一个线程可以操作
// 锁都是会消耗性能的,因为有线程等待
// 锁的范围 :数据的读写部分,范围要竟可能的小
// self : 锁对象,凡是继承自NSObject的对象,都是锁对象.因为内部都有一把锁,默认是开启的
// 锁对象必须是全局的,self是最方便的锁对象
// 局部的锁对象
// NSObject *obj = [[NSObject alloc] init];
// @synchronized(self) {
// 查询余票数
if (self.tickets >0) { // 有票
// 模拟网络延迟
[NSThread sleepForTimeInterval:1.0];
// 卖一张
self.tickets =self.tickets -1;
// 展示余票数
NSLog(@"余票数 %d %@",self.tickets,[NSThreadcurrentThread]);
} else {
// 没票
NSLog(@"没票了");
break;
}
// }
}