iOS中多线程编程示例【code】

来源:互联网 发布:存在主义 知乎 编辑:程序博客网 时间:2022/07/04 23:20
static NSOperationQueue *queue;- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view.    //normal Thread    queue = [[NSOperationQueue alloc] init];    queue.maxConcurrentOperationCount = 2;    for(int i=0;i<20;i++){        NSInvocationOperation *invocation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download:) object:[NSString stringWithFormat:@"%d",i]];        [queue addOperation:invocation];    }                //1.GCD    //1.1 BLOCK    //声明    void (^logBlock)(void);    //define    logBlock = ^{        NSLog(@"hello,block!\n");    };        //callWork    logBlock();            //example prictice    int (^countSum)(int,int);        countSum = ^(int a,int b){        return a+b;    };            printf("---------\ncountSum:---%d\n---------\n",countSum(10,4));            //--------------------------------------------    //GCD    dispatch_async(dispatch_get_global_queue(0, 0), ^{        NSLog(@"GCD:后台执行.......");    });        dispatch_async(dispatch_get_main_queue(), ^{        NSLog(@"GCD:主线程执行....");    });            static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        NSLog(@"GCD:一次执行...");    });        //delay Time run    double delayInSeconds = 5.0;    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);        dispatch_after(popTime, dispatch_get_main_queue(), ^{        NSLog(@"延时5s执行....");    });    }

0 0