美文网首页
iOS 多线程详解

iOS 多线程详解

作者: 依米米一 | 来源:发表于2021-05-24 13:58 被阅读0次

    一、NSThread

    1、创建方法三种

    ...

     /** 方法一,需要start */

     NSThread*thread1 = [[NSThreadalloc] initWithTarget:selfselector:@selector(doSomething1:) object:@"NSThread1"];

    ...

     // 线程加入线程池等待CPU调度,时间很快,几乎是立刻执行

        [thread1 start];

     /** 方法二,创建好之后自动启动 */

    [NSThreaddetachNewThreadSelector:@selector(doSomething2:) toTarget:selfwithObject:@"NSThread2"];

    /** 方法三,隐式创建,直接启动 */

    [selfperformSelectorInBackground:@selector(doSomething3:) withObject:@"NSThread3"];

    - (void)doSomething1:(NSObject*)object {

          // 传递过来的参数

          NSLog(@"%@",object);

          NSLog(@"doSomething1:%@",[NSThread currentThread]);

      }

      - (void)doSomething2:(NSObject*)object {

          NSLog(@"%@",object);

          NSLog(@"doSomething2:%@",[NSThread currentThread]);

      }

      - (void)doSomething3:(NSObject*)object {

          NSLog(@"%@",object);

          NSLog(@"doSomething3:%@",[NSThread currentThread]);

      }

    2、打印当前线程:

      NSLog(@"doSomething----:%@",[NSThread currentThread]);

    3、休眠:

       /** 休眠 */

        //休眠多久

         [NSThreadsleepForTimeInterval:2];

         //休眠到指定时间

         [NSThreadsleepUntilDate:[NSDatedate]];

    4、设置优先级

         thread1.threadPriority;

    二 、GCD(异步dispatch_async,同步dispatch_sync)

    相关文章

      网友评论

          本文标题:iOS 多线程详解

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