线程操作

线程阻塞

  • 当满足某个预定条件时,可以使用休眠或锁阻塞线程执行
    • sleepForTimeInterval:休眠指定时长
    • sleepUntilDate:休眠到指定日期
    • @synchronized(self):乎斥锁
  • 死亡
    • 正常死亡
      • 线程执行完毕
    • 非正常死亡
      • 当满足某个条件后,在线程内部中止执行
      • 当满足某个条件后,在主线程中止线程对象

阻塞

[NSThread sleepForTimeInterval:1.0];

[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0];

死亡

//取消当前的线程
[t3 cancel];

//结束当前的线程
[NSThread exit];
  • 一旦强行终止线程,后续的所有代码都不会被执行
  • 注意:在终止线程之前,应该注意释放之前分配的对象!

线程属性

name - 线程名称

  • 在大的商业项目中,通常需要在程序崩溃时,获取程序准确执行所在的线程

threadPriority - 线程优先级

  • 优先级,是一个浮点数,取值范围从 0~1.0

    • 1.0表示优先级最高
    • 0.0表示优先级最低
    • 默认优先级是0.5
  • 优先级高只是保证 CPU 调度的可能性会高

stackSize - 栈区大小

  • 默认情况下,无论是主线程还是子线程,栈区大小都是 512K
  • 栈区大小可以设置
[NSThread currentThread].stackSize = 1024 * 1024;

isMainThread - 是否主线程


NSThread *t1 = [[NSThread alloc] initWithTarget:self selector:@selector(demo) object:nil];

// 1. 线程名称
t1.name = @"Thread AAA";
// 2. 优先级
t1.threadPriority = 0;

[t1 start];

NSThread *t2 = [[NSThread alloc] initWithTarget:self selector:@selector(demo) object:nil];

// 1. 线程名称
t2.name = @"Thread BBB";
// 2. 优先级
t2.threadPriority = 1;

[t2 start];
}

- (void)demo {
for (int i = 0; i < 10; ++i) {
    // 堆栈大小
    NSLog(@"%@ 堆栈大小:%tuK", [NSThread currentThread], [NSThread currentThread].stackSize / 1024);
}

模拟崩溃
判断是否是主线程
if (![NSThread currentThread].isMainThread) {}
}

通知中心

//通知中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadWillExit:) name:NSThreadWillExitNotification object:nil];

//在线程结束的时候执行一些操作
- (void)threadWillExit:(NSNotification *)n
{
   NSThread *t = [n object];
   NSLog(@"%@结束",t.name);
}

results matching ""

    No results matching ""