iOS 多线程详解

一、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)

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

推荐阅读更多精彩内容