多线程之NSThread

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:第一次写东西,主要用于自己的积累。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容