ios开发经验

多线程之NSThread

2016-04-14  本文已影响34人  YvanLiu

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

上一篇 下一篇

猜你喜欢

热点阅读