ios 多线程的一些方法使用

来源:互联网 发布:js怎么给textarea赋值 编辑:程序博客网 时间:2024/05/22 01:31

这篇GCD写的也不错 http://blog.csdn.net/wildfireli/article/details/18668897

一.简单封装的GCD方法

//在主线程中执行+ (void)executeTaskInMainThread: (void (^)())block{    dispatch_queue_t mainQueue = dispatch_get_main_queue();    dispatch_async(mainQueue, block);}//在子线程中执行+ (void)executeTaskInChildThread: (void (^)())block{    dispatch_queue_t asynQueue = dispatch_queue_create("", NULL);    dispatch_async(asynQueue, block);}

//在子线程中执行+ (void)executeTaskInSubThread: (void (^)())block{    dispatch_queue_t asynQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    dispatch_async(asynQueue, block);}

二:通常,我们可以在global_queue中做一些long-running的任务,完成后在main_queue中更新UI,避免UI阻塞,无法响应用户操作:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{          // long-running task          dispatch_async(dispatch_get_main_queue(), ^{              // update UI          });      });  


、dispatch_barrier_async的使用

dispatch_barrier_async是在前面的任务执行结束后它才执行,而且它后面的任务等它执行完成之后才会执行

例子代码如下:

dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);     dispatch_barrier_async(queue, ^{          NSLog(@"dispatch_barrier_async");      });  

五、dispatch_group_async的使用

dispatch_group_async可以实现监听一组任务是否完成,完成后得到通知执行其他的操作。这个方法很有用,比如你执行三个下载任务,当三个任务都下载完成后你才通知界面说完成的了。下面是一段例子代码:


   1. 创建一个group

    dispatch_group_t group =dispatch_group_create();

   2.发送三个请求

      [self requestDistance:group];

      [selfequestGoodlist:group];

      [selfequestMenu:group];

    3. 为group设置通知一个block,当group关联的block执行完毕后,就调用这个block。类似dispatch_barrier_async。        dispatch_group_notify(group, queue, ^{

//做一些执行完毕的操作

 }); 

 或者,等 三个请求都执行完毕后,来刷新界面的数据

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{

    //在主线程中刷新界面数据

    });

4. 手动管理group关联的block的运行状态(或计数),进入和退出group次数必须匹配

 dispatch_group_enter (group);//进入

 dispatch_group_leave (group);//退出


   比如在上面的三个请求接口中,他们成对出现,具体使用如下:

    dispatch_group_enter(group); //进入

    [TFRequestInterfaceselectPartyInfo:_partyID sucess:^(Info *userInfo) {

        dispatch_group_leave(group);//退出

    } failure:^(NSError *error) {

    }];


六、dispatch_apply

执行某个代码片段N次。

dispatch_apply(5, globalQ, ^(size_t index) {

// 执行5次

});

七、dispatch_after

有时候我们需要等个几秒钟然后做个动画或者给个提示,这时候可以用dispatch_after这个函数:

double delayInSeconds = 2.0;      dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);      dispatch_after(popTime, dispatch_get_main_queue(), ^(void){          // code to be executed on the main queue after delay      });  

dispatch_once

    dispatch_once这个函数,它可以保证整个应用程序生命周期中某段代码只被执行一次

+ (TFTTSSpeakManager *)sharedInstance{    static dispatch_once_t  onceToken;    static TFTTSSpeakManager * sSharedInstance;        dispatch_once(&onceToken, ^{        sSharedInstance = [[TFTTSSpeakManager alloc] init];    });    return sSharedInstance;}





0 0