GCD同步异步测试DEMO

转自 <a target=_blank class="cut cut70" href="http://blog.csdn.net/weisubao/article/details/41958799?utm_source=tuicool&utm_medium=referral" style="color: rgb(51, 51, 51); text-decoration: none; -webkit-transition: 0.25s; transition: 0.25s; outline: none 0px; overflow: hidden; white-space: nowrap; word-break: keep-all; text-overflow: ellipsis; max-width: 69%; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; font-size: 14px; display: inline-block;">http://blog.csdn.net/weisubao/article/details/41958799</a>
/**
 *  因为是异步,所以开通了子线程,但是因为是串行队列,所以只需要开通1个子线程(2),它们在子线程中顺序执行。最常用。
 */
-(void)gcdDemo1{
    dispatch_queue_t q1=dispatch_queue_create("com.hellocation.gcdDemo", DISPATCH_QUEUE_SERIAL);
    for (int i=0; i<10; i++) {
        dispatch_async(q1, ^{
            NSLog(@"%@",[NSThread currentThread]);
        });
    }
}
/**
 *  因为是异步,所以开通了子线程,且因为是并行队列,所以开通了好多个子线程,具体几个,无人知晓,看运气。线程数量无法控制,且浪费。
 */
-(void)gcdDemo2{
    dispatch_queue_t q2=dispatch_queue_create("com.hellocation.gcdDemo", DISPATCH_QUEUE_CONCURRENT);
    for (int i=0; i<10; i++) {
        dispatch_async(q2, ^{
            NSLog(@"%@",[NSThread currentThread]);
        });
    }
}
/**
 *  因为是同步,所以无论是并行队列还是串行队列,都是在主线程中执行
 */
-(void)gcdDemo3{
    dispatch_queue_t q1=dispatch_queue_create("com.hellocation.gcdDemo", DISPATCH_QUEUE_CONCURRENT);
    for (int i=0; i<10; i++) {
        dispatch_sync(q1, ^{
            NSLog(@"%@",[NSThread currentThread]);
        });
    }
}
/**
 *  全局队列和并行队列类似(全局队列不需要创建直接get即可,而导致其没有名字,不利于后续调试)
 */
-(void)gcdDemo5{
    dispatch_queue_t q=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    for (int i=0; i<10; i++) {
        dispatch_sync(q, ^{
            NSLog(@"1-%@",[NSThread currentThread]);
        });
    }
    for (int i=0; i<10; i++) {
        dispatch_async(q, ^{
            NSLog(@"2-%@",[NSThread currentThread]);
        });
    }
}
/**
 *  因为是主线程,所以异步任务也会在主线程上运行(1)。而如果是同步任务,则阻塞了,因为主线程一直会在运行,所以后米的任务永远不会被执行。
 *  主要用处,是更新UI,更新UI一律在主线程上实现
 */
-(void)gcdDemo6{
    dispatch_queue_t q=dispatch_get_main_queue();
//    for (int i=0; i<10; i++) {
//        dispatch_sync(q, ^{
//            NSLog(@"%@",[NSThread currentThread]);
//        });
//    }
	for (int i=0; i<10; i++) {
		dispatch_async(q, ^{
			NSLog(@"%@",[NSThread currentThread]);
		});
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值