iOS 多线程

iOS--多线程-GCD

2016-02-28  本文已影响42人  STONEsh

ViewController.m#

//
//  ViewController.m
//  多线程-GCD
//
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//======================== GCD ===========================
//子线程
    
    dispatch_queue_t queue = dispatch_queue_create("test", NULL);
    
    dispatch_async(queue, ^{//子线程调用的Block
        for (int i = 0; i < 50; i ++) {
            NSLog(@"子线程:%d", i);
        }
      //返回主线程执行,主线程调用此Block
        dispatch_sync(dispatch_get_main_queue(), ^{//主线程调用的Block
            
            if ([NSThread isMainThread]) {
                NSLog(@"是主线程");
            }
        });
        
        
        
    });
    
    
    
    
    
    
//主线程:
    
    for (int i = 0; i < 50; i ++) {
        NSLog(@"主线程:%d", i);
    }
    
    
    
}


/*
 //
 /////dispatch_sync(),同步添加操作。他是等待添加进队列里面的操作完成之后再继续执行。
 
 dispatch_queue_t concurrentQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
 NSLog(@"1");
 dispatch_sync(concurrentQueue, ^(){
 NSLog(@"2");
 [NSThread sleepForTimeInterval:10];
 NSLog(@"3");
 });
 NSLog(@"4");
 输出 :
 
 11:36:25.313 GCDSeTest[544:303] 1
 11:36:25.313 GCDSeTest[544:303] 2
 11:36:30.313 GCDSeTest[544:303] 3//模拟长时间操作
 11:36:30.314 GCDSeTest[544:303] 4
 
 //
 /////dispatch_async ,异步添加进任务队列,它不会做任何等待
 
 dispatch_queue_t concurrentQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
 NSLog(@"1");
 dispatch_async(concurrentQueue, ^(){
 NSLog(@"2");
 [NSThread sleepForTimeInterval:5];
 NSLog(@"3");
 });
 NSLog(@"4");
 输出:
 11:42:43.820 GCDSeTest[568:303] 1
 11:42:43.820 GCDSeTest[568:303] 4
 11:42:43.820 GCDSeTest[568:1003] 2
 11:42:48.821 GCDSeTest[568:1003] 3//模拟长时间操作时间
 */

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

上一篇下一篇

猜你喜欢

热点阅读