多線程的簡單使用,多線程簡單使用

來源:互聯網
上載者:User

多線程的簡單使用,多線程簡單使用

 NSOperationQueue的簡單使用過程:

1.  建立一個NSOperationQueue的對象

2.  建立一個NSOperation的對象

3.  將operation加入到NSOperationQueue中

     MRC 需要手動釋放

4.  release掉operation

 NSOperationQueue *queue = [NSOperationQueue new];

  NSInvocationOperation *operation = [[NSInvocationOperation alloc]

                                        initWithTarget:self

                                        selector:nil)

                                        object:nil];

[queue addOperation:operation];

/***********************************GCD**************************************************/

//一次性執行

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        //code be executed once

    });

 

//延遲調用

    double delayInSeconds = 2.0;

    dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);

    dispatch_after(timer, dispatch_get_main_queue(), ^{

        //code be executed once after delay

    });

    

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

     //code be executed once after delay

    });

 

//自訂queque

    dispatch_queue_t fun = dispatch_queue_create("funfun", NULL);

    dispatch_async(fun, ^{

        // your code

    });

MRC 需要釋放

//dispatch_release(fun);

 

 

//GCD組 同時進行多個任務,任務完成之後再主線程執行其他任務

    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{

        //your code

    });

    dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{

        //your code

    });

       dispatch_group_notify(group, dispatch_get_main_queue(), ^{

        //your code

    });

 

//多線程的安全執行緒

  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{  // 線程鎖   NSLock *lock =  [[NSLock alloc] init];

    [lock lock];

    //your code

    [lock unlock];

    });  dispatch_async(queue, ^{ NSLock *lock =  [[NSLock alloc] init];

    [lock lock];

    //your code

    [lock unlock];

});

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.