zoukankan      html  css  js  c++  java
  • 线程生命周期(状态)

     1     /*
     2      线程的生命周期(状态):
     3      1、新建状态:创建了新线程(alloc init)
     4      2、就绪状态:线程对象添加到“可调度线程池”,等待被CPU调度执行(thread star)
     5      3、运行状态:正在被CPU调度执行(执行一半CPU去执行别的线程,将进入就绪状态)
     6      4、阻塞状态:休眠或等待同步锁(休眠时间到或等到同步锁,进入就绪状态)
     7      5、死亡状态:自然死亡或强制死亡([NSThread exit])
     8      
     9      6、取消状态:线程对象被取消了,“应该是”不能执行的
    10             注:仅仅是线程的一个状态(相当于标记),线程并不会停止
    11      */
     1 // 线程被添加到可调度线程池后,方法的执行时机是由CPU决定的
     2 - (void)demo{
     3     for(NSInteger i = 0; i < 10; i++){
     4         
     5         // 如果当前线程状态为“取消”
     6         if([NSThread currentThread].isCancelled){
     7             // doSomeThing
     8         }
     9         
    10         // 3、运行状态
    11         NSLog(@"%zd  %@",i,[NSThread currentThread]);
    12         
    13         
    14         
    15         if(i == 2){ // 4、阻塞状态
    16             // [NSThread sleepUntilDate:(nonnull NSDate *)]
    17             // [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:5]];
    18             [NSThread sleepForTimeInterval:5];
    19         }
    20         
    21         if(i == 3){ // 5、死亡状态
    22             // 使当前线程强制退出:结束当前线程,在这里相当于return
    23             // 注意:千万不能在主线程调用,会杀死主线程
    24             [NSThread exit];
    25         }
    26     }
    27 }
    28 
    29 - (void)threadDemo{
    30     // 1、新建状态:创建一个线程对象
    31     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo) object:nil];
    32     
    33     // 2、就绪状态:添加到可调度线程池,等待被CPU调度执行
    34     [thread start];
    35     
    36     // 一旦调用此方法,仅仅是线程状态变为取消状态
    37     // 主线程:2秒之后,就调用cancel方法
    38     [NSThread sleepForTimeInterval:2];
    39     [thread cancel];
    40 }
    41 
    42 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    43     [self threadDemo];
    44 }
  • 相关阅读:
    Autofac 依赖注入
    C#高级语法
    @helper
    Spiral Matrix -- LeetCode
    Best Time to Buy and Sell Stock with Cooldown -- LeetCode
    Kth Smallest Element in a Sorted Matrix -- LeetCode
    Number of Connected Components in an Undirected Graph -- LeetCode
    Super Ugly Number -- LeetCode
    Ugly Number II -- LeetCode
    Missing Ranges -- LeetCode
  • 原文地址:https://www.cnblogs.com/panda1024/p/6264819.html
Copyright © 2011-2022 走看看