iOS -- 多线程

来源:互联网 发布:腾讯大数据 会 11.22 编辑:程序博客网 时间:2024/06/03 19:22

获取主线程和当前线程

[NSThread mainThread][NSThread currentThread]

创建子线程主要有下面4种方法:

1.NSThread

[NSThread detachNewThreadSelector:@selector(downloadPictuer)                         toTarget:self                       withObject:nil];

2.GCD(Grand Central Dispatch)

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        [self downloadPictuer];    });

dispatch_get_global_queue第2个参数传0(API规定)。

GCD比NSThread更高效,会由底层分配到多核上去执行。

3.performSelectorInBackground

[self performSelectorInBackground:@selector(downloadPictuer) withObject:nil];

4.NSOperationQueue

待补~


线程间的通信

主要使用下面两种方法:

  • performSelectorOnMainThread
  • performSelector: onThread: withObject: waitUntilDone: modes

eg,

//在主线程中调用showPicture:image[self performSelectorOnMainThread:@selector(showPicture:) withObject:image waitUntilDone:YES];

showPicture函数为

- (void)showPicture:(UIImage *)image {    self.imageView.image = image;    NSLog(@"main thread: %@, current thread: %@",          [NSThread mainThread], [NSThread currentThread]);}

子线程向主线程传递image对象,并触发主线程的showPicture方法

0 0