zoukankan      html  css  js  c++  java
  • 创建线程的三种方式

    创建线程的三种方式

    • 第一种:通过NSThread的对象方法
    • 第二种:通过NSThread的类方法
    • 第三种:通过NSObject的方法
    • 准备在后台线程调用的方法 longOperation:
    - (void)longOperation:(id)obj {
        NSLog(@"%@ - %@", [NSThread currentThread], obj);
    }
    

    方式1:alloc / init - start

    - (void)threadDemo1 {
        NSLog(@"before %@", [NSThread currentThread]);
    
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(longOperation:) object:@"THREAD"];
    
        [thread start];
    
        NSLog(@"after %@", [NSThread currentThread]);
    }
    

    代码小结

    • [thread start];执行后,会在另外一个线程执行 longOperation: 方法
    • 在 OC 中,任何一个方法的代码都是从上向下顺序执行的
    • 同一个方法内的代码,都是在相同线程执行的(block除外)

    方式2:detachNewThreadSelector

    - (void)threadDemo2 {
        NSLog(@"before %@", [NSThread currentThread]);
    
        [NSThread detachNewThreadSelector:@selector(longOperation:) toTarget:self withObject:@"DETACH"];
    
        NSLog(@"after %@", [NSThread currentThread]);
    }
    

    代码小结

    • detachNewThreadSelector 类方法不需要启动,会自动创建线程并执行 @selector 方法

    方式3:分类方法

    - (void)threadDemo3 {
        NSLog(@"before %@", [NSThread currentThread]);
    
        [self performSelectorInBackground:@selector(longOperation:) withObject:@"PERFORM"];
    
        NSLog(@"after %@", [NSThread currentThread]);
    }
    

    代码小结

    • performSelectorInBackground 是 NSObject 的分类方法
    • 会自动在后台线程执行 @selector 方法
    • 没有 thread 字眼,隐式创建并启动线程
    • 所有 NSObject 都可以使用此方法,在其他线程执行方法
  • 相关阅读:
    [NS]运行行两年了,碰到一个没遇见的问题!
    [C++][MFC]关于菜单的一些操作
    [C++][MFC]CFile的一些简单使用
    [CSharp]HTML中的模式窗口
    [C++]堆栈与堆的概念
    [RS]关于ReportingServices的开发
    [JS]在程序中使用IE的模式对话框!
    [WWF][STUDY]向Workflow传入参数
    [学习]极限编程与敏捷开发
    [C++]什么是纯虚函数
  • 原文地址:https://www.cnblogs.com/Ruby-Hua/p/5150028.html
Copyright © 2011-2022 走看看