美文网首页ios开发经验
多线程之NSThread

多线程之NSThread

作者: YvanLiu | 来源:发表于2016-04-14 11:36 被阅读34次

    NSThread

    • 优点:轻量级,更直观的控制线程对象
    • 缺点:需要自己管理线程的生命周期,线程同步,线程枷锁。这会导致一定的性能开销。
      代码
    一. 实例化
        //初始化
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadRun1) object:nil];
        //优先级 0 - 1.0 1.0z最高
        thread.threadPriority  = 1.0;
        //开始线程
        [thread start];
    

    或者使用类方法

        //创建并开启新线程
        [NSThread detachNewThreadSelector:@selector(threadRun2) toTarget:self withObject:nil];
    

    获取当前线程和主线程

        //获取当前线程
        NSThread *thread2 = [NSThread currentThread];
        //获取主线程
        NSThread *main = [NSThread mainThread];
    
    二. 延时执行
        //延时两秒执行
        [NSThread sleepForTimeInterval:2];
    
        NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];  
        [NSThread sleepUntilDate:date];  
        //延时执行
        [self performSelector:@selector(threadRun4) withObject:self afterDelay:2];
    
    三. 线程通讯
        //在指定线程执行
        [self performSelector:@selector(threadRun5) onThread:thread2 withObject:nil waitUntilDone:YES];
        
        //在主线程执行
        [self performSelectorOnMainThread:@selector(threadRun6) withObject:nil waitUntilDone:YES];
        
        //当前线程执行
        [self performSelector:@selector(threadRun7) withObject:nil];
    

    PS:第一次写东西,主要用于自己的积累。

    相关文章

      网友评论

        本文标题:多线程之NSThread

        本文链接:https://www.haomeiwen.com/subject/rxyglttx.html