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)

你可能感兴趣的:(iOS 多线程详解)