• 多线程之NSThread


    关于多线程会有一系列如下:
    多线程之概念解析 

    多线程之pthread, NSThread, NSOperation, GCD

    多线程之NSThread

    多线程之NSOperation

    多线程之GCD

    一,创建线程

    • 动态创建
    /**
     动态创建
     */
    - (void)dynamicCreateThread {
        // 动态创建
        // 动态创建的线程,必须调用 start ,线程才会跑起来
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(dynamicRun:) object:@1];
        thread.threadPriority = 1;//0-1,1的优先级最高
        thread.name = @"dynamic thread";
        [thread start];
        
        // iOS10 以后新添加的方法
        NSThread *newThread = [[NSThread alloc] initWithBlock:^{
            NSLog(@"block operation");
        }];
        [newThread start];
    }
    
    
    
    - (void)dynamicRun:(NSNumber *)index {
        NSLog(@"thread = %@", [NSThread currentThread]);
        NSLog(@"index = %@", index);
        NSLog(@"dynamic run");
        NSLog(@"name = %@", [NSThread currentThread].name);
    }
    • 静态创建

    /** 静态创建 */ - (void)staticCreateThread { // 静态创建 [NSThread detachNewThreadSelector:@selector(staticRun) toTarget:self withObject:nil]; // ios 10以后才出现 [NSThread detachNewThreadWithBlock:^{ [self staticRun]; }]; }

    • 隐式创建
    /**
     隐式创建
     */
    - (void)backgroundCreateThread {
        [self performSelectorInBackground:@selector(backgroundRun) withObject:nil];
    }
    • 线程通信
    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
    
    - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;

    二.属性

     @property (class, readonly, strong) NSThread *currentThread;//获取当前线程

    @property (nullable, copy) NSString *name // 线程名
    @property double threadPriority //优先级,0-1, 1的优先级最高
    @property NSUInteger stackSize // 线程所占用内存
    @property (readonly) BOOL isMainThread // 是否为主线程

    状态相关

    @property (readonly, getter=isExecuting) BOOL executing 
    @property (readonly, getter=isFinished) BOOL finished 
    @property (readonly, getter=isCancelled) BOOL cancelled


    三.API

    + (BOOL)isMultiThreaded;// 判断当前线程是否是多线程
    
    //线程操作
    
    - (void)start;
    
    - (void)cancel;
    
    + (void)exit;
    
    - (void)main;// thread body method
    
    // 线程阻塞
    
    + (void)sleepUntilDate:(NSDate *)date;
    
    + (void)sleepForTimeInterval:(NSTimeInterval)ti;
    
     
    // 获取线程
    @property (class, readonly, strong) NSThread *currentThread;//获取当前线程
    @property (class, readonly, strong) NSThread *mainThread;//获取主线程

    四.自定义NSThread

      注意:  通过静态方法创建的 thread不会执行 main 方法

      











  • 相关阅读:
    textarea回车在多浏览器兼容问题
    windows server平台移动oracle表空间
    奇妙的英文recreate,reproduce,regenerate也不同
    《Inside the C++ Object Model》笔记(1~7章)
    1.4买书问题C#源码
    C#的Compiler Error CS1660
    数学符号表
    C#工程添加了DLL编译运行时却提示”无法加载DLL“的解决方案
    看源代码那些事【转】
    救命的软件,查看你关掉的网站内容
  • 原文地址:https://www.cnblogs.com/shidaying/p/6931333.html
Copyright © 2020-2023  润新知