多线程:串行队列

来源:互联网 发布:java软件工程师就业 编辑:程序博客网 时间:2024/06/09 19:11
////  ViewController.m//  07-串行队列////  Created by gzxzmac on 16/1/29.//  Copyright © 2016年 gzxzmac. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    [self gcdDemo3];}/* 在串行队列上, 如果是同步的,没有开线程,在当前线程上执行任务 如果是异步的,只开一条线程,所有任务都顺序执行 */- (void)gcdDemo3 {    dispatch_queue_t queue = dispatch_queue_create("itcast", DISPATCH_QUEUE_SERIAL);    for (int i = 0; i < 20; ++i) {        dispatch_sync(queue, ^{            NSLog(@"%@ -- %d",[NSThread currentThread],i);        });    }}// 串行同步 : 没有开线程,在当前线程上执行- (void)gcdDemo2 {    dispatch_queue_t queue = dispatch_queue_create("itcast", DISPATCH_QUEUE_SERIAL);    dispatch_sync(queue, ^{        NSLog(@"%@",[NSThread currentThread]);    });}// 串行异步- (void)gcdDemo1 {    // 只开了一条线程,任务一个一个执行    dispatch_queue_t queue = dispatch_queue_create("itcast", DISPATCH_QUEUE_SERIAL);    for (int i = 0; i < 20; ++i) {        dispatch_async(queue, ^{            NSLog(@"%@ -- %d",[NSThread currentThread],i);        });    }}// 创建串行队列- (void)gcdDemo {    // 第一个参数 : 名字,(并不是线程的名字)    // 第二个参数: 队列的类型    dispatch_queue_t queue = dispatch_queue_create("itcast", DISPATCH_QUEUE_SERIAL);    dispatch_async(queue, ^{        NSLog(@"%@",[NSThread currentThread]);    });};@end
0 0
原创粉丝点击